正如标题所说,我在将从基类继承的成员函数指针传递给专门的模板函数时遇到了一些麻烦。
如果我在以继承方法作为参数调用模板函数时没有指定类型,编译器将选择错误的(Base)一个:
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;
}
在这种情况下是否需要调用指定派生类的专用模板函数,还是我做错了什么?
最佳答案
method
从Derived
可见但实际上是 Base
的成员, 因此 &Derived::method
的类型是void (Base::*)()
.
这些语句都打印相同的值:
std::cout << typeid(&Base::method).name() << "\n";
std::cout << typeid(&Derived::method).name() << "\n";
关于C++ 将派生类的成员函数指针作为参数传递时选择了错误的模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51791793/