C++ 将派生 class 的成员函数指针作为参数传递时选择了错误的模板专业化
C++ Wrong template specialization selected when passing member function pointer of derived class as a parameter
正如标题所说,我在将从基础 class 继承的成员函数指针传递给专门的模板函数时遇到了一些麻烦。
如果以继承方法作为参数调用模板函数时不指定类型,编译器会select错误的(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;
}
在这种情况下是否需要调用指定派生的专用模板函数 class 还是我做错了什么?
method
从 Derived
可见,但实际上是 Base
的成员,因此 &Derived::method
的类型是 void (Base::*)()
.
这些语句都打印相同的值:
std::cout << typeid(&Base::method).name() << "\n";
std::cout << typeid(&Derived::method).name() << "\n";
正如标题所说,我在将从基础 class 继承的成员函数指针传递给专门的模板函数时遇到了一些麻烦。
如果以继承方法作为参数调用模板函数时不指定类型,编译器会select错误的(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;
}
在这种情况下是否需要调用指定派生的专用模板函数 class 还是我做错了什么?
method
从 Derived
可见,但实际上是 Base
的成员,因此 &Derived::method
的类型是 void (Base::*)()
.
这些语句都打印相同的值:
std::cout << typeid(&Base::method).name() << "\n";
std::cout << typeid(&Derived::method).name() << "\n";