Search code examples
c++initializer-list

Is it possible to merge 2 initializer_list?


In cpp we can construct objects of some classes with an intializer_list:

std::initializer_list<std::pair<const std::string, int>> il = { {"CPU", 10}, {"GPU", 15} };
std::map<std::string, int> m = il;

But can we merge 2 initializer_lists into 1 then use it to call the constructor? e.g.

std::initializer_list<std::pair<const std::string, int>> il1 = { {"CPU", 10}, {"GPU", 15} };
std::initializer_list<std::pair<const std::string, int>> il2 = { {"RAM", 20} };
std::initializer_list<std::pair<const std::string, int>> il = il1 + il2;
std::map<std::string, int> m = il;

Solution

  • In order to merge two initializer-lists you would need to merge the two referenced sequences. Which means you would need an appropriately sized backing-space with the right lifetime.

    As the size is arbitrary, it would need to be dynamically allocated.
    Additionally, there is no way to determine the proper lifetime.

    All the problems stem from it being a lightweight reference type just like std::span, instead of a much heavier container.


    Instead, consider using the first for initialization and insert the other elements afterwards.