Question

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?

Was it helpful?

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")
;

OTHER TIPS

In C++11, that's fine, although you could simplify it by initialising the map directly rather than using an array.

If you're stuck in the past, then you can't initialise value_type, an alias for a std::pair specialisation, from a braced initialiser list; although some compilers may allow this as a non-standard extension. Instead, you'd need:

const error_code_entry_t error_code_tbl_[] = {
    // Either like this
    error_code_entry_t(ERR_OK, "ERR_OK"),

    // Or like this
    std::make_pair(ERR_RT_OUT_OF_MEMORY, "ERR_RT_OUT_OF_MEMORY"),

    // ...
};
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top