【问题标题】:Init the map of structs with string key使用字符串键初始化结构映射
【发布时间】:2013-02-02 23:34:03
【问题描述】:

我有一个

struct OpDesc {
        std::string  OPName;
        size_t       OPArgsMin;
        bool         IsVaribaleArgsNum;
        bool         IsOPChange;
        std::string  ChangeNodeOP;
        std::string  ChangeNodeLabel;
        bool         IsOPDelete;
        const char*  ErrMsg;
    };

并且想初始化一个std::map<string, OpDesc>

我试过这样做:

typedef std::map<std::string,struct OpDesc> OpDescMap;
OpDescMap opDesc;
opDesc["StoreOp"] = {"StoreOp",2,false,false,"","",false,""};
/// etc.

我无法用 VS10 编译它。我得到:error C2059: syntax error : '{'

如何解决?

【问题讨论】:

    标签: c++ map static struct init


    【解决方案1】:

    您的语法是有效的 C++11(参见 Uniform Initialization),但是 VS10 不支持它。它仅被添加到 VS12(参见 C++ features in VS2012)。一种选择是将编译器升级到更符合 C++11 的编译器。

    如果无法升级,则必须回退到 C++03 语法。您可以使用中间变量:

    OpDesc op = {"StoreOp", 2, false, false, "", "", false, ""};
    opDesc[op.OPName] = op;
    

    或者在你的结构中添加一个构造函数:

    struct OpDesc {
       // ... all fields
       OpDesc(std::string const& opName, size_t opArgsMin, bool isVariableArgsNum,
              bool isOpChange, std::string const& changeNameOp,
              std::string const& changeNodeLabel, bool isOpDelete,
              char const* errMsg)
       : OPName(opName), OPArgsMin(opArgsMin), IsVariableArgsNum(isVariableArgsNum),
         IsOpChange(isOpChange), ChangeNameOp(changeNameOp),
         ChangeNodeLabel(changeNodeLabel), IsOpDelete(isOpDelete),
         ErrMsg(errMsg) {}
    };
    
    opDesc["StoreOp"] = OpDesc("StoreOp", 2, false, false, "", "", false, "");
    

    【讨论】:

    • 语法是OP使用的语法:这是VC10的限制。
    • @AndyProwl 谢谢,我已经更新了我的答案,列出这是 VS10 的不兼容问题。
    【解决方案2】:

    可以通过为OpDesc 创建一个协程器来解决问题

    OpDesc(const std::string&  oPName="StoreOp",
          size_t oPArgsMin = 0,
          bool  isVaribaleArgsNum = false,
          bool  isOPChange=false,
          const std::string&  changeNodeOP = "",
          const std::string&  changeNodeLabel = "",
          bool  isOPDelete = false,
          const char*  errMsg= "" )
      :OPName(oPName),
      OPArgsMin(oPArgsMin),
      IsVaribaleArgsNum(isVaribaleArgsNum),
      IsOPChange(isOPChange),
      ChangeNodeOP(changeNodeOP),
      ChangeNodeLabel(changeNodeLabel),
      IsOPDelete(isOPDelete),
      ErrMsg(errMsg)
    {
    }
    
    OpDescMap opDesc;
    opDesc["StoreOp"] = OpDesc("StoreOp", 2, false, false, "", "", false, "");
    

    【讨论】:

      【解决方案3】:

      @billz 的解决方案的替代方案是构造对象并将其插入到地图中,分两个单独的步骤:

      OpDesc od = { "StoreOp",2,false,false,"","",false,"" };
      opDesc["StoreOp"] = od;
      

      【讨论】:

        【解决方案4】:

        您可以使用其他编译器:您的源代码适用于 clang++ V 3.3 和 gcc 4.7.2。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-02-17
          • 1970-01-01
          • 1970-01-01
          • 2012-01-17
          • 2017-05-26
          • 2012-06-12
          • 1970-01-01
          相关资源
          最近更新 更多