如何使用模板专业化来查找成员函数参数类型等
How can I use template specialisation to find member function argument types etc?
我肯定以前见过这样的描述,但现在我一辈子都找不到。
给定一个具有某种形式的成员函数的类,例如:
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 worldn";
}
};
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中获得类型,例如gcc或Boost中的typeof
。Typeof:
Types<typeof(&Foo::Bar)>
或者升级到C++11并使用标准decltype
:
Types<decltype(&Foo::Bar)>
相关文章:
- 如何使用指针传递给函数的数组中对象的函数成员
- c++构造函数成员初始化:传递参数
- 创建 std::函数,它返回具有函数成员值的变量.分段错误
- 如何在C++通过公共函数访问私有函数成员?
- 解释了构造函数成员初始化列表
- 调用std::函数成员时内存损坏
- 是否可以为模板类的模板函数成员设置别名?
- 捕获 lambda 函数C++成员变量
- 构造函数成员初始值设定项跨成员列出,安全吗?
- 获取与在模板参数中传递的函数成员类型相同的类
- 如何从公共函数成员访问地图私有成员
- C 构造函数成员分配优化
- 使用命名空间进行函数成员定义
- 函数成员作为 CUDA 内核的参数
- 模板基类函数成员的别名
- 函数成员中用于void和继承的enable_if
- 头文件中是否定义了一个很长的Class函数成员
- 类内/构造函数成员初始化
- 使用指向部分专用函数成员的指针自动填充向量
- 指向函数成员的指针