考虑这段代码:
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 个值之一(Type1
、Type2
),我希望 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/