Howtouseinitializerlisttoinitializestd::variant?

The non-variant version of initializer list works good:

std::map<int, double> a = {{1,0.1}};

But the variant version doesn't:

std::variant<std::map<int, double>, int> b = {{1,0.1}};

Is there a way to initialize b using initializer list? If not, what is the best way to initialize it?

回答

One way is to be more specific:

std::variant<std::map<int, double>, int> b = std::map<int, double>{{1,0.1}};

Not ideal, but the compiler cannot choose the right overload of std::variant constructor from a <brace-enclosed initializer list>. Because of how the relevant std::variant constructor is defined:

template< class T >
constexpr variant( T&& t ) noexcept(/* see below */);

T&& t cannot possibly match a <brace-enclosed initializer list>, only a value of a specific type.


以上是Howtouseinitializerlisttoinitializestd::variant?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>