c++ - 根据数字参数更改模板成员?

标签 c++ templates

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

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

关于c++ - 根据数字参数更改模板成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31140302/

相关文章:

templates - 我应该如何检查 Ember 中 ArrayController 的内容是否脏

c++ - 依赖项目中的部分 C++ 模板特化

c++ - 如果类型来自 std,是否可以创建一个特征来回答?

c++ - 在 Compact 7 中使用 wlantool.exe 连接到 wifi 网络失败,错误代码为 1814

c++ - 存储唯一元素但在 C++ 中回答对另一个排序的查询的数据结构

javascript - 如何获得在 Visual Studio 2015 中运行的 Cordova 项目模板?

c++ - 基本类型和复杂类型的通用 for 循环

c++ - 从 Visual C++ 资源文件获取 FILEVERSION

c++ - 副作用/ volatile /复制构造函数/析构函数

c++ - 解析一个词的字符串