2

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?

Chowlett
  • 45,935
  • 20
  • 116
  • 150

2 Answers2

4

You can use value initialization to solve this problem.

struct Foo
{
    char x;
};

std::map<int, Foo> myMap =
{
    { 1, {} },
    { 2, {} }
};
François Andrieux
  • 28,148
  • 6
  • 56
  • 87
  • I thought I could, and I tried it, and it didn't work... which is why I came here. Further prodding shows it works _in general_, but not if the value-type is not copy-constructible. Do you know why not? – Chowlett Jan 16 '17 at 17:00
  • @Chowlett Regarding your follow-up question, I will refer you to [this answer](http://stackoverflow.com/a/7232135/7359094). – François Andrieux Jan 16 '17 at 17:06
  • 1
    Ah. That would explain it. Am I therefore completely stuffed for initialising in this fashion? I note that even `myMap = { { 1, Foo() } };` fails, for presumably exactly the same reason. – Chowlett Jan 16 '17 at 17:09
  • @Chowlett If you don't have a copy constructor, you will have a bad time with initializer lists. Consider asking a separate question on how to work around this problem. Include what you've tried so far. – François Andrieux Jan 16 '17 at 17:17
  • additional info: Since `C++11` – Sandburg Mar 29 '19 at 11:25
0

You could make a function that returns an instance of "yourNamespace::subLibrary::moreLevels::justBecause::Thing".