C++17中模板参数中auto的优点 [英] Advantages of auto in template parameters in C++17

查看:44
本文介绍了C++17中模板参数中auto的优点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 C++17 中(可能)引入的模板参数中 auto 的优点是什么?

What are the advantages of auto in template parameters that will (possibly) be introduced with C++17?

当我想实例化模板代码时,它只是auto的自然扩展吗?

Is it just a natural extension of auto when I want to instantiate template code?

auto v1 = constant<5>;      // v1 == 5, decltype(v1) is int
auto v2 = constant<true>;   // v2 == true, decltype(v2) is bool
auto v3 = constant<'a'>;    // v3 == 'a', decltype(v3) is char

我还能从这个语言功能中获得什么?

What else do I gain from this language feature?

推荐答案

模板 <auto> 功能 (P0127R1) 在芬兰奥卢举行的 ISO C++ 2016 会议上被 C++ 接受.

The template <auto> feature (P0127R1) was accepted into C++ in the ISO C++ 2016 meeting in Oulu, Finland.

模板参数中的 auto 关键字可用于指示非类型参数,其类型是在实例化点推导出的.将其视为更方便的书写方式会有所帮助:

An auto keyword in a template parameter can be used to indicate a non-type parameter the type of which is deduced at the point of instantiation. It helps to think of this as a more convenient way of writing:

template <typename Type, Type value>

例如

template <typename Type, Type value> constexpr Type constant = value;
constexpr auto const IntConstant42 = constant<int, 42>;

现在可以写成

template <auto value> constexpr auto constant = value;
constexpr auto const IntConstant42 = constant<42>;

您不再需要明确说明类型的地方.P0127R1 还包括一些简单但很好的使用带有可变参数模板参数的 template <auto> 的示例非常方便,例如对于编译时列表常量值的实现:

where you don't need to explicitly spell out the type any more. P0127R1 also includes some simple but good examples where using template <auto> with variadic template parameters is very handy, for example for implementations of compile-time lists constant values:

template <auto ... vs> struct HeterogenousValueList {};
using MyList1 = HeterogenousValueList<42, 'X', 13u>;

template <auto v0, decltype(v0) ... vs> struct HomogenousValueList {};
using MyList2 = HomogenousValueList<1, 2, 3>;

在 C++1z 之前的版本中,HomogenousValueList 可以简单地写成

In pre-C++1z, while HomogenousValueList could be simply written as

template <typename T, T ... vs> struct Cxx14HomogenousValueList {};
using MyList3 = Cxx14HomogenousValueList<int, 1, 2, 3>;

如果不将值包装在其他一些模板中,就不可能编写等效的 HeterogenousValueList,例如:

writing an equivalent of HeterogenousValueList would not be possible without wrapping the values in some other templates, for example:

template <typename ... ValueTypes> struct Cxx14HeterogenousValueList {};
using MyList4 = Cxx14HeterogenousValueList<constant<int, 42>,
                                           constant<char, 'X'> >;

这篇关于C++17中模板参数中auto的优点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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