auto在C++17引入的模板参数中有哪些优点(可能)?
当我想实例化模板代码时,这仅仅是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我还能从这个语言特性中得到什么呢?
发布于 2016-06-26 23:54:07
template <auto>特性(P0127R1)在芬兰奥卢举行的国际标准化组织2016年C++会议上被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>;在pre++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'> >;发布于 2016-07-28 15:22:29
实际上,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几天前我自己也被同样的误解绊倒了。
发布于 2018-02-04 14:24:48
下面是另一个示例(最初由 @Rakete1111作为未知类型模板参数的答案提出):
在不知道大小的类型的情况下提取大小值:
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;
}https://stackoverflow.com/questions/38026884
复制相似问题