在如下所示的模板中,我希望调用Run(&Base::foo)
成功而不需要两次命名 Base 类型(就像在编译Run<Base>(&Base::foo)
调用中所做的那样)。我可以拥有吗?可能不添加大量Boost标头?
使用提供的代码,我收到以下错误:
prog.cpp:26: error: no matching function for call to ‘Run(bool (Base::*)())’
(您可以在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?
}