我敢肯定我以前见过这个描述,但现在找不到了。
给定一个具有某种形式的成员函数的类,例如:
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?
编辑:
我正在使用快速委托(delegate),回调静态绑定(bind)到成员函数。
我有以下模型,我相信它静态绑定(bind)到成员函数:
#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();
}
但是 - 如何以上述方式将其作为特化?
最佳答案
除了不属于该类型的额外 MemFunc
外,您几乎已经搞定了。
template<typename RetType, typename ClassType, typename Arg0>
struct Types<RetType (ClassType::*)(Arg0)> // <-- no MemType
{
typedef RetType return_type;
typedef ClassType class_type;
// typedef MemFunc mem_func; // <-- remove this line
typedef Arg0 argument_0;
};
但是,您不能使用
Types<&Foo::Bar>
因为 Foo::Bar 是一个成员函数指针,而不是它的类型。您需要一些编译器扩展来获取 C++03 中的类型,例如typeof
in gcc或 Boost.Typeof :
Types<typeof(&Foo::Bar)>
或升级到 C++11 并使用标准 decltype
:
Types<decltype(&Foo::Bar)>
关于c++ - 如何使用模板特化来查找成员函数参数类型等?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8932803/