"
2016年ISO C++会议在芬兰奥卢接受了template <auto>
特性(P0127R1)。
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'> >;
template < auto >
会让这些提问者满意。 - cpplearnerstd::vector<auto> v{1,2,3,4,5};
,而困难的事情则是将可调用类型作为模板参数(尤其是 lambda 表达式)。 - emsrauto
应该放在定义上,而不是使用的地方。 - Nicol Bolasauto
不会与其冲突。 - Jonathan Wakely