Search code examples
c++initializer-list

Initialize a container inside a class/struct with std::initializer_list


I never was really able to work with std::initializer_list, and I'd like to change that. So I'm trying to do this really simple thing, which is to forward the initializer list to initialize a struct member. I tried a lot of things, but there is a example :

#include <unordered_map>
#include <functional>

struct Foo
{
    using U_Func = std::function<void()>;
    using U_MapFunc = std::unordered_map<std::string, U_Func>;

    U_MapFunc  funcMap;

    Foo(std::initializer_list<U_MapFunc::value_type> mapParams)
        : funcMap(mapParams)
    {}
};

Foo test(
    {"", []() {}}
);

Someone can tell me how I should write this code?


Solution

  • This is basically not much more than a typo.

    You only provided one value_type in the initializer_list, but it is supposed to be, well, a list of value_types. So, add another set of braces:

    Foo test(
      {{"", []() {}}}
    );
    

    Or write it like this for added clarity:

    Foo test{
        // Element list under here
        {
            // One element here
            {"", []() {}}
        }
    };
    

    The resulting std::initializer_list can be copied (though the things inside it won't be copied) so your "forwarding" works just fine.