Dam*_*ian 51 c++ templates auto c++17
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
Run Code Online (Sandbox Code Playgroud)
我还从这个语言功能中获得了什么?
mce*_*ceo 59
该template <auto>
功能(P0127R1)在芬兰奥卢的ISO C++ 2016会议上被C++接受.
auto
模板参数中的关键字可用于指示非类型参数,其类型在实例化时推断出.将此视为一种更方便的写作方式有助于:
template <typename Type, Type value>
Run Code Online (Sandbox Code Playgroud)
例如,
template <typename Type, Type value> constexpr Type constant = value;
constexpr auto const IntConstant42 = constant<int, 42>;
Run Code Online (Sandbox Code Playgroud)
现在可以写成
template <auto value> constexpr auto constant = value;
constexpr auto const IntConstant42 = constant<42>;
Run Code Online (Sandbox Code Playgroud)
你不需要明确拼写出类型的地方.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>;
Run Code Online (Sandbox Code Playgroud)
在pre-C++ 1z中,虽然HomogenousValueList
可以简单地写成
template <typename T, T ... vs> struct Cxx14HomogenousValueList {};
using MyList3 = Cxx14HomogenousValueList<int, 1, 2, 3>;
Run Code Online (Sandbox Code Playgroud)
HeterogenousValueList
如果不将值包装在某些其他模板中,则无法编写等效项,例如:
template <typename ... ValueTypes> struct Cxx14HeterogenousValueList {};
using MyList4 = Cxx14HeterogenousValueList<constant<int, 42>,
constant<char, 'X'> >;
Run Code Online (Sandbox Code Playgroud)
m-j*_*j-w 12
实际上,mceo(原始)答案中的实际值的情况明确地未被涵盖为非类型模板参数.
template <auto ... vs> struct HeterogenousValueList {};
using MyList1 = HeterogenousValueList<42, 'X', 1.3f>;
Run Code Online (Sandbox Code Playgroud)
请参阅上述提案中给出的示例:修改§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
Run Code Online (Sandbox Code Playgroud)
几天前我自己也偶然发现了同样的错误观念.
这是另一个示例(最初由@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;
}
Run Code Online (Sandbox Code Playgroud)
...但事实并非如此:-(
概念技术auto
规范允许带有模板参数占位符的函数参数,例如:
void printPair(const std::pair<auto, auto>& p) {
std::cout << p.first << ", " << p.second << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
但后来它在 C++20 规范中被删除了。
这是一个巧妙的用法... 我希望它能再次出现在 C++26 中!
归档时间: |
|
查看次数: |
16898 次 |
最近记录: |