根据数字参数更改模板成员

Change template members based on numeric parameters?

本文关键字:成员 数字 参数      更新时间:2023-10-16

我希望能够完成这样的事情:

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

一种方法是对每一套可能的价值观进行明确的专业化,但这显然并不理想。有人知道更好的方法吗?

使用std::conditional。这需要C++11,但你可以很容易地编写自己的:

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

或者在C++14中:

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