首页 > 解决方案 > 如何使用范围枚举模板参数设置数组别名的长度而不进行强制转换

问题描述

我的目标是为基于枚举模板参数设置长度的a创建一个别名。std::array我设法依靠枚举的转换使其工作,如下面的代码所示。

#include <array>
#include <iostream>

enum class StateRepresentation
{
    Log2 = 1,
    One_hot = 16
};

template <StateRepresentation R>
using State = std::array<int, static_cast<int>(R) * 16>;

int main(void)
{
    const auto curr_repr = StateRepresentation::One_hot;
    auto b = State<curr_repr>{};
    std::cout << "Representation value: " << static_cast<int>(curr_repr) << '\n';
    std::cout << "Array length: " << b.size() << '\n';

    return 0;
}

是否有可能实现相同但不依赖于static_cast获取枚举数的数值?

我尝试了一些模板专业化的方法,如下所示,但未能使其工作:

template <>
using State<StateRepresentation::Log2> = std::array<int, 1 * 16>;

template <>
using State<StateRepresentation::One_hot> = std::array<int, 16 * 16>;

标签: c++templates

解决方案


您可以使用conditional_t来打开枚举类的哪个成员用于实例化:

template <StateRepresentation R>
using State = std::conditional_t<R == StateRepresentation::Log2,
                                 std::array<int, 1 * 16>,
                                 std::array<int, 16 * 16>>;

这避免了枚举类成员需要与要在std::array.

正如评论中所指出的,您还可以在数组参数本身中使用三元条件来选择您想要的大小

template <StateRepresentation R>
using State = std::array<int, (R == StateRepresentation::Log2 ? 1 : 16) * 16>;

推荐阅读