C++ Logo

std-proposals

Advanced search

Using `= default; ` Constructors to Remove Boilerplate Constructors

From: Alex Brachet-Mialot <alexbrachetmialot_at_[hidden]>
Date: Thu, 6 Feb 2020 00:00:06 -0500
Hi all,

I just wanted to float this idea that I have had for a while.

I find many constructors often follow this format Type(a_t a, b_t b) :
a(a), b(b) {}. This can get tedious quickly and look very ugly. Such
types can sometimes be aggregates which solves this problem, but not
always, aggregates have prerequisites that very few types can
realistically follow.

I was thinking that `= default` could be used in this circumstance.

class C {
    int a;
    int b;

public:
    C(int b, int a) = default; // Equivalent to : a(a), b(b) {}
    C(int a, int c) = default; // Doesn't know what to do with c, error
};

In the first case nothing is ambiguous to the compiler, the order of
arguments is not relevant only their names.

I think this would be pretty useful because we've all had constructors
become unwieldily long which follow this pattern, especially when
variable names are more descriptive than a or b.

To my knowledge there is no precedent for a keyword or any language
feature which depends on variable names, but I think this is a useful
change and also fairly trivial change for compilers. I would be happy
to go and implement this in clang if people are interested in the
proposal and would like to see an implementation.

Let me know if you have thoughts.

Best,
Alex

Received on 2020-02-05 23:03:04