考虑以下代码:
#include <variant> struct x { int y; }; int main() { std::variant<x> v(std::in_place_type<x>,{3}); /*1*/ return std::get<x>(v).y; }
这不会编译,也不会从行/ * 1 * /中删除{},即使聚合初始化也是如此
x a{3}; x b({3});
适用于“类似构造函数”的形式.我可以以某种方式让std :: variant初始化器知道使用聚合初始化构造结构的可能性,而不必为我的实际案例中可能使用的每个结构编写无聊的样板构造函数吗?
我希望这可以工作,不知何故,根据cppreference,两个重载(5)和(6)都说
Constructs a variant with the specified alternative T and initializes the contained value with the arguments […]
如果重要的话,我正在使用GCC 7.
解决方法
除了添加构造函数之外,没有解决方法.标准规定了你提到的过载,分别为
[variant.ctor]19和
[variant.ctor]23:
Effects: Initializes the contained value as if direct-non-list-initializing an object of type
T
with the argumentsstd::forward<Args>(args)...
.Effects: Initializes the contained value as if direct-non-list-initializing an object of type
T
with the argumentsil,std::forward<Args>(args)...
.
您始终可以使用以下方法复制或移动对象:
std::variant<x> v(std::in_place_type<x>,x{3}); // or more clear and does the same thing std::variant<x> v(x{3});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。