繁体   English   中英

C++17中模板参数中auto的优点

[英]Advantages of auto in template parameters in C++17

C++17 将(可能)引入的模板参数中的auto有哪些优点?

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

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

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

在芬兰奥卢举行的 ISO C++ 2016 会议上, template <auto>特性 ( P0127R1 ) 被 C++ 接受。

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

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>非常方便,例如对于编译时列表常量值的实现:

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可以简单地写成

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

如果不将值包装在其他一些模板中,则无法编写HeterogenousValueList的等效项,例如:

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

实际上,mceo 的(原始)答案中的实际值的情况明确不包含在非类型模板参数中。

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

请参阅上述提案中给出的示例:修改 §14.3.2 第 2 段:

template<auto n> struct B { /* ... */ };
B<5> b1;   // OK: template parameter type is int
B<'a'> b2; // OK: template parameter type is char
B<2.5> b3; // error: template parameter type cannot be double

几天前我偶然发现了同样的误解。

这是另一个示例(最初由@Rakete1111 提供,作为未知类型模板模板参数的答案):

在不知道其类型的情况下提取 SIZE 的值:

template<std::size_t SIZE>
class Foo {};

template <template<auto> class T, auto K>
auto extractSize(const T<K>&) {
    return K;
}

int main() {
    Foo<6> f1;
    Foo<13> f2;
    std::cout << extractSize(f1) << std::endl;
    std::cout << extractSize(f2) << std::endl;
}

C++20 似乎增加了另一种用法

...但它没有:-(

概念技术规范允许带有auto模板参数占位符的函数参数,例如:

void printPair(const std::pair<auto, auto>& p) {
    std::cout << p.first << ", " << p.second << std::endl;
}

但后来在 C++20 规范中被删除了。

这是一个巧妙的用法......我希望它会在 C++23 中再次出现!

请参阅: “auto”作为函数参数的模板参数占位符

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM