Search code examples
c++stdmapvalue-type

braces around scalar initializer for type const GCC


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;
}

the code shown above throws "error: braces around scalar initializer for type âconst error_code_entry_tâ" Can anyone help me fix it please?


Solution

  • You seem to have an C++03 compiler, since that should compile in C++11. Since error_code_entry_t is the value_type of your map, it is in fact a std::pair<const in, const char*> (Yes, the const for the key type is correct). That is not an aggregate, so you cannot initialize it like that. To fix the error at hand, you could try the following:

    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" ), 
        // ...
    };
    

    But since you want to put them into a map anyways, I'd consider 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")
    ;