proposal?
Primary constructors for C++
Problem:
C++11 allows in-class member initialization. However, in-class initializers have no access to constructor parameters, which makes them useless in many scenarios. Example:
template<typename T, unsigned INIT>
class MyClass {
public:
MyClass(unsigned init) {}
private:
T x0 {INIT}; // OK
T x1 {init}; // Error
}
So essentially in this case C++ favors compile-time template interfaces over run-time constructor interfaces.
Possible solution: Primary constructors (similar to Scala, Kotlin and abandoned C# proposal)
We can designate one constructor as primary. Parameters of primary constructor should be visible to in-class initializers. All other constructors must call primary constructor in their constructor initialization list.
For example, we can use following syntax (similar to Scala/Kotlin):
template<typename T, unsigned INIT>
class MyClass (unsigned init) {
public:
// secondary ctor
MyClass() : MyClass(42) {}
private:
T x0 {INIT}; // OK
T x1 {init}; // OK
}
Чем этот подход лучше чем самому написать primary constructor и в нем поля проинициализировать?
Обсуждают сегодня