[英]How to use initializer list to initialize std::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?有没有办法使用初始化列表初始化 b ? 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>
.不理想,但编译器无法从
<brace-enclosed initializer list>
中选择正确的std::variant
构造函数重载。 Because of how the relevantstd::variant
constructor is defined:因为相关的
std::variant
构造函数是如何定义的:
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. T&& t
不可能匹配<brace-enclosed initializer list>
,只能匹配特定类型的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.