[英]Can I use condition in type alias in C++20?
As C++ expands to fuse normal computations and type computations I wonder if there is a way to have something like this work?随着 C++ 扩展以融合正常计算和类型计算,我想知道是否有办法让这样的工作?
static const int x = 47;
using T = (x%2) ? int : double;
I know I can use the decltype on a template function that returns the different types based on if constepr, but I wanted something short like my original example.我知道我可以在模板 function 上使用 decltype,该模板根据 if constepr 返回不同的类型,但我想要一些简短的东西,就像我原来的例子一样。
template<auto i> auto determine_type(){
if constexpr(i%2) {
return int{};
} else {
return double{};
}
}
note: I am happy to use C++20注意:我很高兴使用 C++20
You can use:您可以使用:
using T = std::conditional_t<(i % 2), int, double>;
For more complex constructions, your approach has too many limitations on the type - would be better to do it this way:对于更复杂的结构,您的方法对类型有太多限制 - 最好这样做:
template<auto i>
constexpr auto determine_type() {
if constexpr (i%2) {
return std::type_identity<int>{};
} else {
return std::type_identity<double>{};
}
}
using T = /* no typename necessary */ decltype(determine_type<i>())::type;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.