1

For example, nlohmann json has a way of converting an aggregate initializer list to a JSON object:

json j = {
  {"pi", 3.141},
  {"happy", true},
  {"name", "Niels"},
  {"nothing", nullptr},
  {"answer", {
    {"everything", 42}
  }},
  {"list", {1, 0, 2}},
  {"object", {
    {"currency", "USD"},
    {"value", 42.99}
  }}
};

and c++ std::map also has a aggeragte initalizer list

{
{"one": 1},
{"two": 2}
}

I'm curious about how you can write a custom (aggregate) initalizer list initalizer

3
  • 1
    There is no such thing as an "aggregate initializer list" constructor. This is just an application of list-initialization. Each of those braced-init-lists is just a means for calling a constructor. Commented Apr 29, 2020 at 23:03
  • yes, but how do can i write a custom initializer for it (if I can)? Commented Apr 29, 2020 at 23:07
  • You can look inside json.hpp to see how it writes its constructor Commented Apr 30, 2020 at 1:04

1 Answer 1

1

It is easy to learn howtos in the standard library.

Look at the std::map constructor:

map( std::initializer_list<value_type> init,
     const Compare& comp = Compare(),
     const Allocator& alloc = Allocator() );

value_type is

std::pair<const Key, T>, Key is std::string, T is int

So the constructor is

map( std::initializer_list<std::pair<std::string, int>> init,
     const Compare& comp = Compare(),
     const Allocator& alloc = Allocator() );

and can be used like with

{
  std::pair("one", 1),
  std::pair("two", 2),
}

Then look at std::pair constructor

pair( const T1& x, const T2& y );

It can be constructed like

std::pair<std::string, int> a{"one", 1};

or

std::pair<std::string, int> a = {"one", 1};

Taking into consideration all above, a map can be constructed like with

{
{"one", 1},
{"two", 2}
}
Sign up to request clarification or add additional context in comments.

5 Comments

what about the more complex JSON example? if you can explain it, ill accept your answer!
@FloweyTF: It's the same thing, just using a different type. It's nothing special. Just look at the json type's constructor.
More complex JSON can be done with std::map<std::string, std::any>
Or class JSONItem : public std::variant<std::string, bool, int, std::map<std::string, JSONItem>, std::vector<JSONItem>> {}; using JSON = std::map<std::string, JSONItem>;
I'd rather not use std::variant because its for c++17, but I guess?

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.