NoSenseEtAl
NoSenseEtAl

Reputation: 30068

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?

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.

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

note: I am happy to use C++20

Upvotes: 1

Views: 341

Answers (1)

Barry
Barry

Reputation: 303347

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;

Upvotes: 2

Related Questions