c++ - 动态迭代静态信息

标签 c++ templates specialization

假设我有一些专门用于每种枚举类型的类:

enum MyEnum {
  EnumA = 0, EnumB, EnumSize
};

template <enum MyEnum> 
class StaticEnumInfo {

};

template <> 
class StaticEnumInfo<EnumA>{
  typedef bool type;
  const std::string name = "EnumA";
};

template <> 
class StaticEnumInfo<EnumB>{
  typedef int type;
  const std::string name = "EnumB";
};

是否可以遍历所有名称并打印它们? 我想写这样的东西:

for(MyEnum i = EnumA; i < EnumSize; ++i){
    // Doesn't make sense, I know.
    std::cout << StaticEnumInfo<i>::name << std::endl;
}

我知道我可以在其他地方创建一个映射来解决这种映射(对于字符串,而不是类型......)

我没有权限提升

最佳答案

直到正确expansion statements可用,您可以随时这样做:

template <typename T, T... S, typename F>
constexpr void for_sequence(std::integer_sequence<T, S...>, F&& f) {
    (static_cast<void>(f(std::integral_constant<T, S>{})), ...);
}

然后像这样使用它:

for_sequence(
    std::make_integer_sequence<int, EnumSize>{},
    [&](auto i) {
        constexpr auto index = static_cast<MyEnum>(int{i});
        std::cout << StaticEnumInfo<index>::name << std::endl;
    }
);

但是要小心,因为它只有在所有枚举成员都是顺序的情况下才有效。

Live example

关于c++ - 动态迭代静态信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57775192/

相关文章:

C++基础模板题

c++ - 类型推导失败 : shared_ptr of derived template to base template as function argument

c++ - 通过指向虚基类的指针访问模板类的模板成员函数?

asp.net-mvc-3 - 可重用的编辑器模板,带有用于业务对象的 DropDownList

c++ - 为什么 C++ const 引用可以折叠成非常量引用

c++ - 类模板特化的问题

c++ - 使用 ssl c/c++ 的客户端和服务器通信 - SSL 协议(protocol)不起作用

c++ - 使用刷新的输入从 C++ 调用 Matlab

c++ - 如何将 Mat 复制到 ROI?

C++ : How to specialize a member function for a template Array-like class A to deal with A<A<T>>?