std::variant
强类型语言的一个特定就是当要使用一个变量时,必须要确定该变量的类型,并且一旦声明后,就不可更改.
但是 C++17 中收录来自 Boost 库的 variant,它通过一系列复杂的模板,绕过了这个规则.当然,如果使用这个类型,性能会存在些微的损失:
variant v, w;
v = 12;
int i = get(v);
w = get(v);
w = get<0>(v); // same effect as the previous line
w = v; // same effect as the previous line
get(v); // ill formed
get<3>(v); // ill formed
try {
get(w); // will throw.
}
catch (bad_variant_access&) {}
Template arguments with auto
在 C++17 中已经可以在模板中使用auto
进行自动推导类型了.
template constexpr auto constant = x;
auto v1 = constant<5>; // v1 == 5, decltype(v1) is int
auto v2 = constant; // v2 == true, decltype(v2) is bool
auto v3 = constant<'a'>; // v3 == 'a', decltype(v3) is char