Short answer, as you've seen, is: you can't do that.
I think what you really want is this:
std::map<std::string, Foo> map;
int main()
{
map["bar"] = Foo();
If you really need the initialization to execute before main()
you will often see examples like this:
namespace {
struct StaticInitHelper {
StaticInitHelper() { map["bar"] = Foo(); }
} _helper_obj;
}
However, now you have a new problem which is that there's no guarantee that map
is created before _helper_obj
. One way around this is to combine them:
namespace {
struct StaticInitHelper : public std::map<std::string, Foo> {
StaticInitHelper() { (*this)["bar"] = Foo(); }
} map;
}
Inheriting from STL container classes is generally not recommended, however. Note that this example hides any other constructors and the STL base class does not have a virtual destructor. This would be considered a "hack" by many, and should really be avoided.
Yet another alternative is to define the class with a std::map
:
namespace {
struct StaticInitHelper {
StaticInitHelper() { map["bar"] = Foo(); }
std::map<std::string, Foo> map;
} map_holder;
}
map_holder.map.find(...
But of course this complicates any use of the map.
Update:
I forgot to mention another option, using boost::assign
:
#include <boost/assign/list_of.hpp>
map<int,int> map = boost::assign::map_list_of(1,2)(2,3)(3,4)(4,5)(5,6);
I can't find information on whether that's safe on a static object, though.