Calling initializer_list constructor via make_unique/make_shared

std::make_unique is a function template which deduces the argument types which are passed to the object constructor. Unfortunately, braced lists are not deducible (with an exception for auto declarations), and so you cannot instantiate the function template when that missing parameter type.

You can either not use std::make_unique, but please don’t go that route – you should avoid naked news as much as you can, for the children’s sake. Or you can make the type deduction work by specifying the type:

  • std::make_unique<Foo>(std::initializer_list<std::string>({"Hello", "World"}))

  • std::make_unique<Foo, std::initializer_list<std::string>>({"Hello", "World"})

  • auto il = { "Hello"s, "World"s }; auto ptr = std::make_unique<Foo>(il);

The last option uses the special rule for auto declarations, which (as I hinted above) do in fact deduce an std::initializer_list.

Leave a Comment