在如下所示的模板中,我希望调用Run(&Base::foo)成功,而无需将Base类型命名两次(如编译Run<Base>(&Base::foo)调用中所做的那样).我可以吗?可能没有添加大量的Boost标头?
使用提供的代码,我得到一个错误:
prog.cpp:26: error: no matching function for call to ‘Run(bool (Base::*)())’
Run Code Online (Sandbox Code Playgroud)
(你可以在http://ideone.com/8NZkq上摆弄这个片段):
#include <iostream>
class Base {
public:
bool foo() { return true; }
};
Base* x;
template<typename T>
struct Traits {
typedef bool (T::*BoolMethodPtr)();
};
template<typename T>
void Run(typename Traits<T>::BoolMethodPtr check) {
T* y = dynamic_cast<T*>(x);
std::cout << (y->*check)();
}
int main() {
Base y;
x = &y;
Run<Base>(&Base::foo);
Run(&Base::foo); // why error?
}
Run Code Online (Sandbox Code Playgroud)