c – 我可以避免为std :: variant中的每个结构显式编写构造函数吗?

考虑以下代码
#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 arguments std​::​forward<Args>(args)....

Effects: Initializes the contained value as if direct-non-list-initializing an object of type T with the arguments il,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});

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...