[英]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.