How to pass std::map as a default constructor parameter

recipriversexclusion picture recipriversexclusion · Nov 8, 2010 · Viewed 11.8k times · Source

I haven't been able to figure this out. It's easy to create two ctors but I wanted to learn if there's an easy way to do this.

How can one pass a std::map as the default parameter to a ctor, e.g.

Foo::Foo( int arg1, int arg2, const std::map<std::string, std::string> = VAL)

I've tried 0, null, and NULL as VAL, none of the work because they are all of type int, g++ complains. What is the correct default to use here?

Or is this kind of thing not a good idea?

Answer

aschepler picture aschepler · Nov 8, 2010

The correct expression for VAL is std::map<std::string, std::string>(). I think that looks long and ugly, so I'd probably add a public typedef member to the class:

class Foo {
public:
  typedef std::map<std::string, std::string> map_type;
  Foo( int arg1, int arg2, const map_type = map_type() );
  // ...
};

And by the way, did you mean for the last constructor argument to be a reference? const map_type& is probably better than just const map_type.