用于定义类型定义的可变参数模板(使用 C++11)
Variadic template to define a typedef (using C++11)
我刚刚定义了 4 种差异最小的不同 typedef,我想知道是否有办法使用模板更有效地做到这一点。
我的 typedef 的形式是:typedef Type1 (*pf)(Type2, Type3, ...)
如何模板化此类型定义?
只需要Type1
。
我手动写:
typedef int (*pf)(int)
typedef bool (*pf)()
typedef char (*pf)(bool, int)
我正在寻找类似的东西:
template <Type T1,Type...Rest>
typedef T1 (*pf)(Type...Rest)
这是对的吗?
是的,当然,两行(可能是单行,具体取决于您的代码风格(:
template<class T, class... X>
using fptr_t = T (*)(X...);
这采用了一种称为alias template
的技术 http://en.cppreference.com/w/cpp/language/type_alias:
(如类型别名(,而是定义用于定义新类型的模板。当与不同的类型一起使用时,它会基于此模板提供类型定义。这是C++11功能。
您可以通过推迟
到专门用于函数签名的模板类来创建易于阅读的函数指针类型def:
#include <iostream>
namespace detail {
// define the template concept
template<class Sig>
struct function_ptr;
// specialise on pointer to function of a given signature
template<class Ret, class...Args>
struct function_ptr<Ret (Args...)>
{
using type = Ret (*)(Args...);
};
}
// defer to template specialisation
template<class Sig>
using function_ptr = typename detail::function_ptr<Sig>::type;
int test1(int) { return 0; }
bool test2() { return false; }
char test3(bool, int) { return 'a'; }
int main()
{
using pfi = function_ptr <int (int)>;
using pfv = function_ptr <bool ()>;
using pfbi = function_ptr <char (bool, int)>;
auto pt1 = pfi(test1);
auto pt2 = pfv(test2);
auto pt3 = pfbi(test3);
std::cout << pt1(100) << std::endl;
std::cout << pt2() << std::endl;
std::cout << pt3(true, 100) << std::endl;
}
相关文章:
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 使用用户定义函数的字符串反转
- 我的项目不会像"undefined reference to `grpc::g_core_codegen_interface'"那样使用未定义的引用错误进行编译
- 标准是否使用多余的大括号(例如 T{{{10}}})定义列表初始化?
- 使用命名空间时出现多个定义错误
- 使用VS Code和CMake Tools运行自定义命令
- 使用mysql c++连接器的未定义引用
- 我的自定义使用 std::unordered_map 的性能非常慢
- 在 C++17 中,是否未定义使用无锁原子学保护从信号处理程序传递的数据?
- MSVC:无法识别的模板声明/定义(使用 Clang/GCC 编译)
- 如何在内核中定义/使用函数
- 定义使用此类型作为模板参数的类型和函数
- 在声明后对成员函数定义使用decltype
- K&R 风格的函数定义使用 g++ 编译
- 如何在 Windows 窗体中为事件函数定义使用单独的.cpp文件
- 定义/使用由预设组件构建的类(在c++中)
- 如何定义使用五倍相同参数类型的函数类型
- 在c++中使用整数排序(自定义使用std:: Sort)
- 错误LNK2005(已经在对象中定义)使用派生类的boost序列化
- 定义使用递归查找最后一位偶数的函数