定义 typedef 的可变参数模板(使用 C++11) [英] Variadic template to define a typedef (using C++11)

查看:39
本文介绍了定义 typedef 的可变参数模板(使用 C++11)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚定义了 4 个不同的 typedef,它们的差异很小,我想知道是否有办法使用模板来更有效地做到这一点.

I have just defined 4 different typedefs with minimal differences and I'm wondering if there's way to use templates to do this more efficiently.

我的 typedef 是这样的:typedef Type1 (*pf)(Type2, Type3, ...)

My typedef is of the form: typedef Type1 (*pf)(Type2, Type3, ...)

如何模板化这个 typedef?

How do I template this typedef?

仅需要 Type1.

我手动编写:

typedef int (*pf)(int)
typedef bool (*pf)()
typedef char (*pf)(bool, int)

我正在寻找类似的东西:

I'm looking for something like:

template <Type T1,Type...Rest>
typedef T1 (*pf)(Type...Rest)

正确吗?

推荐答案

是的,当然,两行(根据你的代码风格可能是单行):

Yes, sure, two lines (could be single line depending on your code style):

template<class T, class... X>
using fptr_t = T (*)(X...);

这采用了一种称为别名模板的技术:http://en.cppreference.com/w/cpp/language/type_alias

This employs a technique which is called alias template: http://en.cppreference.com/w/cpp/language/type_alias

别名模板在某种意义上类似于类模板,它不定义新类型(就像类型别名那样),相反,它定义了一个用于定义新类型的模板.当与不同类型一起使用时,它为您提供基于此模板的类型定义.这是 C++11 特性.

Alias template is akin to class template in a sense that it doesn't define new type (like type alias does), instead, it defines a template for defining new types. When used with different types, it gives you type definition based on this template. This is C++11 feature.

这篇关于定义 typedef 的可变参数模板(使用 C++11)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆