如何从C ++模板中的方法类型推导类类型? [英] How to deduce class type from method type in C++ templates?
问题描述
在如下所示的模板中,我想调用 Run(& Base :: foo)
成功,而不需要将Base类型命名两次在编译 Run< Base>(& Base :: foo)
调用中)。我可以有吗?可能没有添加大量的 Boost 标头?
In templates as shown below, I would like the call Run(&Base::foo)
succeed without the need to name the Base type twice (as is done in the compiling Run<Base>(&Base::foo)
call). Can I have that? Possibly without adding a ton of Boost headers?
使用提供的代码,我得到一个错误:
With the provided code, I get an error of:
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?
}
推荐答案
中的
这是因为可能有这样的代码:
The T
in Traits<T>::BoolMethodPtr
is in a non-deduced context, so the compiler will not deduce automatically from the call what type T should be.
This is because there could be code like this:
template<typename T>
struct Traits {
typedef bool (T::*BoolMethodPtr)();
};
template<>
struct Traits<int> {
typedef bool (Base::*BoolMethodPtr)();
};
Run(&Base::foo); /* What should T be deduced to? Base and int are both equally possible */
如果你不需要 Traits< T>
类,您可以写运行
为:
If you can do without the Traits<T>
class, you can write Run
as:
template<class Class>
void Run(bool (Class::*check)()) {
Class* y = dynamic_cast<Class*>(x);
std::cout << (y->*check)();
}
在此上下文中, c>可以推导为
Base
这篇关于如何从C ++模板中的方法类型推导类类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!