3
我敢肯定,我已经看过这个描述过,但不能为我的生活找到它现在。如何使用模板特化来查找成员函数参数类型等?
考虑一类具有某种形式的成员函数,例如:
int Foo::Bar(char, double)
如何使用模板和各种特来推断构成类型,如:
template<typename Sig>
struct Types;
// specialisation for member function with 1 arg
template<typename RetType, typename ClassType, etc...>
struct Types<RetType (ClassType::*MemFunc)(Arg0)>
{
typedef RetType return_type;
typedef ClassType class_type;
typedef MemFunc mem_func;
typedef Arg0 argument_0;
etc...
};
// specialisation for member function with 2 args
template<typename RetType, typename ClassType, etc...>
struct Types<RetType (ClassType::*MemFunc)(Arg0, Arg1)>
{
typedef RetType return_type;
typedef ClassType class_type;
typedef MemFunc mem_func;
typedef Arg0 argument_0;
typedef Arg0 argument_1;
etc...
};
这样当我用我的上述成员函数实例化类型时,例如:
Types<&Foo::Bar>
它解析为th e正确的专业化,并将声明相关的typedef?
编辑:
我玩弄快速与代表静态绑定到一个成员函数回调。
我有以下的样机,我相信没有静态绑定的成员函数:
#include <iostream>
template<class class_t, void (class_t::*mem_func_t)()>
struct cb
{
cb(class_t *obj_)
: _obj(obj_)
{ }
void operator()()
{
(_obj->*mem_func_t)();
}
class_t *_obj;
};
struct app
{
void cb()
{
std::cout << "hello world\n";
}
};
int main()
{
typedef cb < app, &app::cb > app_cb;
app* foo = new app;
app_cb f (foo);
f();
}
但是 - 如何得到这个在上面的方式专业化?
遗憾的是这项工作的整点是,我想静态绑定到一个成员函数,所以可以说优化器可以通过函数指针边界进行优化。请问使用decltype可以达到这个目的吗? –
'decltype'只返回对象的类型,而不是指针本身。你是否想要[快速委托](http://www.codeproject.com/KB/cpp/ImpossiblyFastCppDelegate.aspx)? – kennytm
我确实 - 看到编辑的问题。谢谢 –