hammil
hammil

Reputation: 149

Change template members based on numeric parameters?

I'd like to be able to accomplish something like this:

template<int size>
struct myStruct
{
    (size > 5 ? int64_t : int32_t) value;
};

One way of doing it would be to make an explicit specialisation for every possible set of values, but this obviously isn't ideal. Is anyone aware of a better way?

Upvotes: 2

Views: 69

Answers (1)

TartanLlama
TartanLlama

Reputation: 65620

Use std::conditional. This requires C++11, but you could easily write your own:

template<int size>
struct myStruct
{
    typename std::conditional<(size > 5), int64_t, int32_t>::type
          value;
};

Or in C++14:

template<int size>
struct myStruct
{
    std::conditional_t<(size > 5), int64_t, int32_t> value;
};

Upvotes: 4

Related Questions