我可以在C ++ 20的类型别名中使用条件吗?

问题描述 投票:0回答:1

随着C ++的扩展以融合普通计算和类型计算,我想知道是否有办法进行类似的工作?

static const int x = 47;

using T = (x%2) ? int : double;

我知道我可以在模板函数上使用decltype,该模板函数根据constepr返回不同的类型,但是我想像我的原始示例一样简短一些。

template<auto i> auto determine_type(){
    if constexpr(i%2) {
        return int{};
    } else {
        return double{};
    }
}

注意:我很高兴使用C ++ 20

c++ template-meta-programming constexpr c++20
1个回答
1
投票

您可以使用:

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;
© www.soinside.com 2019 - 2024. All rights reserved.