How to decide on type in template argument (i.e. ternary operator at compile time)?

60 views Asked by At

I want some easy, light solution to such syntaxis:

template <bool is_true>
class A {
    B<is_true ? int : float> var;  // B is just some other templated class
};

And I do not want something of that kind (though, it looks normal, I just want everything to look needed and not to create single-time structures and declare their specializations):

template <bool>
struct HelperClass {
    using type = void;
};

template <>
struct HelperClass<true> {
    using type = int;
};

template <>
struct HelperClass<false> {
    using type = float;
};

// 'HelperClass<is_true>::type' instead of ternary operator
1

There are 1 answers

1
Ted Lyngmo On BEST ANSWER

The idiomatic solution is using std::conditional:

template <bool is_true>
class A {
    B<std::conditional_t<is_true, int, float>> var;
};