我正在測驗以下代碼:
#include <iostream>
template<typename T>
class A {
public:
void koo(T) { std::cout << "Hello world!"; }
};
template <typename T>
class B : public A<T> {
public:
void pun(T i) { koo(i); }
};
int main() {
B<int> boo;
boo.pun(5);
}
編譯資訊為:
main.cpp:12:24: error: ‘koo’ was not declared in this scope, and no declarations were found by argument-dependent lookup at the point of instantiation [-fpermissive]
12 | void pun(T i) { koo(i); }
| ~~~^~~
main.cpp:12:24: note: declarations in dependent base ‘A’ are not found by unqualified lookup
main.cpp:12:24: note: use ‘this->koo’ instead
我知道我可以使用this->koo(i)or避免這個錯誤A<T>::koo(i),但我想了解為什么會發生這個編譯錯誤。
我認為koo在pun定義中是一個依賴名稱,根據依賴名稱/查找規則“模板中使用的依賴名稱的查找被推遲到模板引數已知”。在main函式中,B<int> boo;將模板引數設定為int。那為什么 ADL 對函式運算式不起作用koo(i)呢?———————————————————————————————————
讓我們暫時把 ADL 放在一邊。如果我更改void pun(T i) { koo(i); }為void pun(T i) { goo(i); },現在新的編譯資訊是:
main.cpp:12:24: error: ‘goo’ was not declared in this scope; did you mean ‘koo’?
12 | void pun(T i) { goo(i); }
| ~~~^~~
| koo
為什么兩種情況的編譯資訊不同?新錯誤根本沒有提到“引數相關查找”。
uj5u.com熱心網友回復:
ADL 是引數相關查找。在其引數的關聯命名空間中查找函式名稱。 int沒有關聯的命名空間,因此不會發生 ADL。即使它確實發生了,它也只會找到自由函式,因此不會找到您的方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/326455.html
上一篇:C 何時在模板定義中衰減
下一篇:如何在類級別專門化模板化類
