我可以在 C++20 的类型别名中使用条件吗?
Can I use condition in type alias in C++20?
随着 C++ 扩展到融合普通计算和类型计算,我想知道是否有办法让这样的东西工作?
static const int x = 47;
using T = (x%2) ? int : double;
我知道我可以在模板函数上使用 decltype,returns 基于 if constepr 的不同类型,但我想要像我原来的例子一样简短的东西。
template<auto i> auto determine_type(){
if constexpr(i%2) {
return int{};
} else {
return double{};
}
}
注意:我很高兴使用 C++20
您可以使用:
using T = std::conditional_t<(i % 2), int, double>;
对于更复杂的构造,您的方法对类型有太多限制 - 最好这样做:
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;
随着 C++ 扩展到融合普通计算和类型计算,我想知道是否有办法让这样的东西工作?
static const int x = 47;
using T = (x%2) ? int : double;
我知道我可以在模板函数上使用 decltype,returns 基于 if constepr 的不同类型,但我想要像我原来的例子一样简短的东西。
template<auto i> auto determine_type(){
if constexpr(i%2) {
return int{};
} else {
return double{};
}
}
注意:我很高兴使用 C++20
您可以使用:
using T = std::conditional_t<(i % 2), int, double>;
对于更复杂的构造,您的方法对类型有太多限制 - 最好这样做:
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;