且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何保留隐式声明的聚合初始化构造函数?

更新时间:2022-12-16 08:17:48

没有默认的聚合初始化构造函数。



聚合初始化仅在聚合上发生。除其他外,聚合是没有(用户提供的)构造函数的类型。



做您想做的正确方法是使工厂函数以您特殊的方式构造您的类型。



这样,类型可以保持聚合,但是有一种简便的方式可以按照您想要的方式对其进行初始化。



在需要时给类型构造函数强制用户调用构造函数来构造它。否则,您只需使用工厂功能。


Suppose I have a class like this:

struct X {
  char buf[10];
};
X x{"abc"};

This compiles. However, if I add user defined constructors to the class, this implicitly declared aggregate initialization constructor will be deleted:

struct X {
  char buf[10];
  X(int, int) {}
};
X x{"abc"}; // compile error

How can I declare that I want default aggregate initialization constructor, just like that for default constructor X()=default? Thanks.

There is no "default aggregate initialization constructor".

Aggregate initialization only happens on aggregates. And aggregates are types that, among other things, don't have (user-provided) constructors. What you're asking for is logically impossible.

The correct means of doing what you want is to make a factory function to construct your type in your special way. That way, the type can remain an aggregate, but there's a short-hand way for initializing it the way you want.

You give a type a constructor when you want to force users to call a constructor to construct it. When you don't, you just use factory functions.