c++ - 将 const GCC 类型的标量初始值设定项括起来

标签 c++ stdmap value-type

typedef std::map<int, const char*> error_code_tbl_t;
typedef error_code_tbl_t::value_type error_code_entry_t;
const error_code_entry_t error_code_tbl_[] = {
    { ERR_OK              , "ERR_OK" },
    { ERR_RT_OUT_OF_MEMORY, "ERR_RT_OUT_OF_MEMORY" }, 
    // ...
};
const error_code_tbl_t error_code_tbl( begin(error_code_tbl_)
                                     , end  (error_code_tbl_) );

const char* err2msg(int code)
{
    const error_code_tbl_t::const_iterator it = error_code_tbl.find(code);
    if(it == error_code_tbl.end())
      return "unknown";
    return it->second;
}

上面显示的代码抛出“错误:大括号围绕 âconst error_code_entry_tâ 类型的标量初始值设定项”任何人都可以帮我解决这个问题吗?

最佳答案

你似乎有一个 C++03 编译器,因为它应该在 C++11 中编译。 自 error_code_entry_tvalue_type你的 map ,它实际上是一个std::pair<const in, const char*> (是的,键类型的常量是正确的)。那不是一个聚合,所以你不能像那样初始化它。要修复手头的错误,您可以尝试以下操作:

const error_code_entry_t error_code_tbl_[] = {
    error_code_entry_t( ERR_OK              , "ERR_OK" ),
    error_code_entry_t( ERR_RT_OUT_OF_MEMORY, "ERR_RT_OUT_OF_MEMORY" ), 
    // ...
};

但是既然你想把它们放到 map 中,我会考虑 boost.assign:

#include <boost/assign/list_of.hpp>

const error_code_tbl_t error_code_tbl = boost::assign::map_list_of
  (ERR_OK              , "ERR_OK")
  (ERR_RT_OUT_OF_MEMORY, "ERR_RT_OUT_OF_MEMORY")
;

关于c++ - 将 const GCC 类型的标量初始值设定项括起来,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18275655/

相关文章:

c# - .net - 锁定盒装值而不是新对象

c++ - 如何检查一个大结构中的所有字段都由编译器初始化

c++ - 析构函数被调用两次,而没有复制构造函数或赋值运算符被调用

c++ - Boost 侵入式 Hook

c++ - 模板类型参数的模板参数必须是一个类型

wpf - 列表框的选择错误,其中列表项是值类型/结构并包含重复项?

c++ - 成员变量的更新值未反射(reflect)在 pthread 的线程路由函数中

c++ - int 和元组的静态 STL 映射返回 0

STL - 检查 std::map 的所有值是否相等的最简单方法

swift - 我们应该如何初始化结构和类中存储的属性?