Search code examples
c++initializer-liststd-variant

Can't call function with variant parameter using initializer_list


I'm not so skilled in using std::variant and couldn't completely understand all constructor cases.

using map_type = std::multimap<std::string, std::string>;
using union_type = std::variant<std::string, map_type>;

void foo(union_type)
{
...
}

void foo2(map_type)
{
...
}

int main()
{
  foo({ {"key", "val"} }); // gives error "no instance of constructor"
  foo2({ {"key", "val"} }); // works fine
  foo2(map_type{ {"key", "val"} }); // works fine
}

As I can deduce forth constructor is called here, but can't understand what condition is not satisfied. Could someone explain, please?

P.S. Is there some article or source to read more information and examples of using variant?


Solution

  • Template argument deduction for multimap constructor template fails because braced-init-lists do not have a type.

    You have to provide this information explicitly, creating an unnamed temporary object which in most cases will exist in compile-time only (for your code):

    foo(map_type{ { "key", "value" } });