Bob*_*Bob 1 c++ templates typedef
我刚刚定义了4个不同的typedef,差别很小,我想知道是否有办法使用模板更有效地完成这项工作.
我的typedef格式如下: typedef Type1 (*pf)(Type2, Type3, ...)
我如何模板这个typedef?
只是Type1需要.
我手动写:
typedef int (*pf)(int)
typedef bool (*pf)()
typedef char (*pf)(bool, int)
Run Code Online (Sandbox Code Playgroud)
我正在寻找类似的东西:
template <Type T1,Type...Rest>
typedef T1 (*pf)(Type...Rest)
Run Code Online (Sandbox Code Playgroud)
那是对的吗?
是的,当然,两行(可能是单行,具体取决于您的代码风格):
template<class T, class... X>
using fptr_t = T (*)(X...);
Run Code Online (Sandbox Code Playgroud)
这采用了被称为技术alias template:http://en.cppreference.com/w/cpp/language/type_alias
别名模板在某种意义上类似于类模板,它不定义新类型(如类型别名),而是定义用于定义新类型的模板.当与不同类型一起使用时,它会根据此模板为您提供类型定义.这是C++ 11的功能.