3

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?

2 Answers 2

4

You can use value initialization to solve this problem.

struct Foo
{
    char x;
};

std::map<int, Foo> myMap =
{
    { 1, {} },
    { 2, {} }
};
Sign up to request clarification or add additional context in comments.

5 Comments

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 Regarding your follow-up question, I will refer you to this answer.
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 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.
additional info: Since C++11
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.