当其他构造函数存在时,如何强制创建默认序列构造函数?

kov*_*rex 2 c++ constructor default c++11

从C++ 11开始,我们有这个很棒的功能,它允许我们避免为所有小类创建显式构造函数,例如:

class A
{
public:
  A() = default;
  A(int x, int y) : x(x), y(y) {} // bloat
  int x = 0, y = 0;
};
..
A a(1,2);
Run Code Online (Sandbox Code Playgroud)

所以我们现在可以这样写:

class A
{
public:
  int x = 0, y = 0;
};
..
A a{1,2}; // using the sequence constructor created by the compiler, great
Run Code Online (Sandbox Code Playgroud)

问题出现了,当我还有其他我想要使用的构造函数时,例如:

class A
{
public:
  A() = default;
  A(Deserialiser& input) : a(input.load<int>()), b(input.load<int>()) {}
  int x = 0, y = 0;
};
...
A a{1, 2}; // It doesn't work now, as there is another constructor explicitly specified
Run Code Online (Sandbox Code Playgroud)

问题是,如何强制编译器创建默认序列构造函数?

Som*_*ude 6

与第二个示例的不同之处在于您正在进行聚合初始化.

使用第一个和第三个示例,不再可能进行聚合初始化(因为该类具有用户定义的构造函数).

使用第一个示例,然后调用双参数构造函数.使用第三个示例,找不到合适的构造函数,您将收到错误.


注意:在C++ 11中,第二个示例也无法进行聚合初始化,因为C++ 11不允许内联初始化非静态成员.在C++ 14中删除了这个限制.(有关详细信息,请参阅上面的链接参考.)