[英]C++ Wrong template specialization selected when passing member function pointer of derived class as a parameter
如標題所述,將從基類繼承的成員函數指針傳遞給專門的模板函數時遇到了一些麻煩。
如果在使用繼承的方法作為參數調用模板函數時未指定類型,則編譯器將選擇錯誤的(基本)之一:
struct Base {
void method() {
}
};
struct Derived: public Base {
void other_method() {
}
};
template <typename T> void print_class_name(void (T::*func)()) {
std::cout << "Unknown" << std::endl;
}
template <> void print_class_name<Base>(void (Base::*func)()) {
std::cout << "Base" << std::endl;
}
template <> void print_class_name<Derived>(void (Derived::*func)()) {
std::cout << "Derived" << std::endl;
}
int main(int argc, char** argv) {
print_class_name(&Base::method); // output: "Base"
print_class_name(&Derived::method); // output: "Base"???
print_class_name(&Derived::other_method); // output: "Derived"
print_class_name<Derived>(&Derived::method); // output: "Derived"
return 0;
}
在這種情況下是否需要調用專門的模板函數來指定派生類,否則我做錯了嗎?
從Derived
可見該method
,但實際上它是Base
的成員,因此&Derived::method
的類型為void (Base::*)()
。
這些語句都打印相同的值:
std::cout << typeid(&Base::method).name() << "\n";
std::cout << typeid(&Derived::method).name() << "\n";
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.