【发布时间】:2012-01-19 20:28:34
【问题描述】:
我确定我以前见过这种描述,但现在我一辈子都找不到。
给定一个具有某种形式的成员函数的类,例如:
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>
它解析为正确的特化,并声明相关的 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();
}
但是 - 如何以上述方式将其作为专业化?
【问题讨论】:
标签: c++ templates metaprogramming