Search code examples
c++initializer-listdefault-constructor

Initialize std::map, using default-constructed values


If I have a std::map<int, char>, it's nice and easy to initialise:

std::map<int, char> myMap = 
{
  { 1, 'a' },
  { 2, 'b' }
};

If my value-type has a default constructor, I can initialise it like so:

struct Foo
{
  char x;
};

std::map<int, Foo> myMap =
{
  { 1, Foo() },
  { 2, Foo() }
};

But suppose my value-type has a default constructor, but is unwieldy to type:

std::map<int, yourNamespace::subLibrary::moreLevels::justBecause::Thing> myMap = 
{
  // What goes here? I don't want to type
  // yourNamespace::subLibrary::moreLevels::justBecause::Thing again.
};

Short of a using declaration to make the value-type more keyboard-friendly, is there some way to initialise the map with a set of keys, all of which use a default-constructed yourNamespace::subLibrary::moreLevels::justBecause::Thing? How can I signal that I want the mapped value to be default-constructed of its type?


Solution

  • You can use value initialization to solve this problem.

    struct Foo
    {
        char x;
    };
    
    std::map<int, Foo> myMap =
    {
        { 1, {} },
        { 2, {} }
    };