首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >std::使用键映射为带有枚举成员的模板结构。

std::使用键映射为带有枚举成员的模板结构。
EN

Stack Overflow用户
提问于 2017-07-26 19:37:00
回答 1查看 488关注 0票数 0

我想让我的应用程序的std::map的键不是int的,而是更强的类型为模板的非类型的enum定义为struct的成员。下面的第一个程序展示了我的应用程序目前如何使用map的概念,它编译并运行ok。

代码语言:javascript
复制
#include <map>

template< int >
struct NummedMap
{
  typedef std::map< int, NummedMap > NumableMap;

  NummedMap() {}

  NumableMap numableMap;
};

int main()
{
  NummedMap< 3 > numableMap3;
  NummedMap< 4 > numableMap4;
  numableMap3.numableMap[ 3 ] = numableMap3;
  numableMap4.numableMap[ 4 ] = numableMap4;

  return 0;
}

第二个程序显示了我想如何编写我的应用程序的map,但我缺少一些关于非类型模板的概念,以及为什么< enum EnumT >int不同。

代码语言:javascript
复制
#include <map>

struct Enums1 // a struct containing one kind scoped enums
{ 
  enum class Action
  {
    AAAA,
    BBBB
  };
};

struct Enums2 // a struct containing another kind scoped enums
{
  enum class Action
  {
    CCCC,
    DDDD
  };
};

template< enum EnumT >
struct EnummedMap // a struct containing a map whose key is non-type templateable
{
  typedef std::map< EnumT, EnummedMap > EnumableMap; // error C2065: 'EnumT': undeclared identifier

  EnummedMap() {}

  EnumableMap enumableMap;
};

int main()
{
  EnummedMap< Enums1::Action > enummedMap1; // error C2993: illegal type for non-type template parameter 
  EnummedMap< Enums2::Action > enummedMap2; // error C2993: illegal type for non-type template parameter 
  enummedMap1.enumableMap[ Enums1::Action::AAAA ] = enummedMap1; // error C2678: binary '[': no operator found which takes a left-hand operand of type
  enummedMap2.enumableMap[ Enums2::Action::CCCC ] = enummedMap2; // error C2678: binary '[': no operator found which takes a left-hand operand of type

  return 0;
}

我不明白为什么EnumableMap的密钥是未声明的,或者为什么Enums1::Action的功能不像int键。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-26 19:56:32

代码语言:javascript
复制
template< enum EnumT >
struct EnummedMap // a struct containing a map whose key is non-type templateable
{
  typedef std::map< EnumT, EnummedMap > EnumableMap; 

非类型模板参数(在本例中是旧样式枚举)是单个值,根据定义,它不是类型,但是std::map希望键是类型,而不是值。若要完成此工作,请将"enum“更改为"typename":

代码语言:javascript
复制
template<typename EnumT > // << *** HERE ***
struct EnummedMap // a struct containing a map whose key is non-type templateable
{
    typedef std::map< EnumT, EnummedMap > EnumableMap; 
    EnummedMap() {}

    EnumableMap enumableMap;
};

然而,这允许非枚举类型.如果要阻止除枚举类型以外的所有用途,可以使用static_assert:

代码语言:javascript
复制
#include <type_traits>
//...
template<typename EnumT>
struct EnummedMap 
{
    static_assert(std::is_enum_v<EnumT>); // c++17
    //static_assert(std::is_enum<EnumT>::value, ""); // c++11

    typedef std::map< EnumT, EnummedMap > EnumableMap;
    EnummedMap() {}

    EnumableMap enumableMap;
};

如果将非枚举作为模板参数传递,那么它将不会编译。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45336004

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档