c++ - 根据 C++11 中的模板参数选择数组大小?

标签 c++ c++11 templates template-meta-programming

考虑这段代码:

enum class EnumType
{
  Type1,
  Type2
};

constexpr std::size_t the_length;

template <EnumType T>
int function()
{
  std::array<uint8_t, the_length> x;
  //some code here that uses x 
}

我希望数组 x 的长度根据类型 T 具有不同的值。例如,如果 T 可以采用 2 个值之一(Type1Type2),我希望 the_length 具有如果 T==Type1 则值为 10,如果 T==Type2 则值为 20。这可以在 C++11 中完成吗?谢谢

最佳答案

古老的三元运算符有什么问题?

template <EnumType T>
int function()
{
  std::array<SomeType, T == EnumType::Type1 ? 10u : 20u> x;
}

如果T是一个typename,而不是某种类型的值,你只需要改变测试

template <typename T>
int function()
{
  std::array<T, std::is_same<SomeType1, T>::value ? 10u : 20u> x;
}

关于c++ - 根据 C++11 中的模板参数选择数组大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56728351/

相关文章:

c++ - 合并两个 LinkedList 而不创建一个新的 LinkedList

c++ - libclang 获取成员声明

c++ - 数字的立方根,C++

c++ - memory_order_relaxed 无法按 C++ 并发实际代码中的预期工作

c++ - decltype 和静态模板方法

ios - xcode根据文件模板从物理文件夹创建组

c++ - 如何 cudaMemcpy __device__ 初始化的 var

c++ - 将非静态数据成员与常量成员进行比较

javascript - 将 jquery/js 模板存储在单独的文件中

C++ - auto 和 decltype 的替代方案