Unable to initialize const unordered_map<string, variant<int, float>> using initializer list

Viewed 174

So here is the function:

void spawn(const param &para) {
   // ...
}

The param is typedef std::unordered_map<std::string, std::variant<int, float>> param;

And here is how i call it:

spawn({{"x", 450}, {"y", 324}, {"vel", 1.0}, {"increaser", 0.05}, {"direction", 120}});

And here is the error:

no instance of constructor "std::unordered_map<_Key, _Tp, _Hash, _Pred, _Alloc>::unordered_map [with _Key=std::string, _Tp=std::variant<int, float>, _Hash=std::hash< std::string >, _Pred=std::equal_to< std::string >, _Alloc=std::allocator<std::pair<const std::string, std::variant<int, float>>]" matches the argument list -- argument types are: ({...}, {...}, {...}, {...}, {...})

If I change param to initializer_list, it works but I would need to convert it into param later on. If I use make_pair, it returns another error.

So how can I fix this problem?

I'm currently using GCC 11.0 and VSCode.

1 Answers

The value type of your unordered_map is std::variant<int, float>, but in your brace init list, you're passing float instead of a double. This conversion from float to a variant is not allowed.

Either change your value type to std::variant<int, double>, or pass literals of float type, e.g. 1.5f instead of 1.5.

The minimized issue in code is

std::variant<int, float> v = 1.5f;  // ok
std::variant<int, double> v = 1.5;  // ok
std::variant<int, float> v = 1.5;   // error
Related