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

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

问题描述

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

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

此语言功能?

推荐答案

模板< auto> P0127R1 )被接受到C ++中在芬兰Oulu的ISO C ++ 2016会议。

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 saying:

template <typename Type, Type value>

例如,

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

现在可以写为

template <auto value> constexpr auto constant = value;
using 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 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>;

在pre-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'> >;

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

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