Change template members based on numeric parameters?

时间:2015-06-30 13:56:42

标签: c++ templates

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?

1 个答案:

答案 0 :(得分:4)

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;
};