EN VI

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

2024-03-13 04:30:05
C++ - How to decide on type in template argument (i.e. ternary operator at compile time)?

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

Solution:

The idiomatic solution is using std::conditional:

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

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login