C++ Logo

std-proposals

Advanced search

Re: Variables in constructor member initializer list

From: Edward Catmur <ecatmur_at_[hidden]>
Date: Wed, 1 Sep 2021 10:57:52 +0100
On Wed, 1 Sept 2021 at 10:23, Artyom Lebedev via Std-Proposals <
std-proposals_at_[hidden]> wrote:

> You are right, I missed this feature. However, it is still a matter of
> convenience. Besides passing list of parameters, you also need to ensure
> the delegating constructor signature is not colliding with any other
> constructor, requiring constructions like this:
>
> class MyClass {
> public:
> const int a, b, c;
>
> MyClass(int someBaseValue)
> : MyClass(SomeHeavyOperation(someBaseValue), ConstructorTag())
> {}
>
> private:
> struct ConstructorTag {};
>
> MyClass(int someDerivedValue, ConstructorTag) :
> a(someDerivedValue * 2),
> b(someDerivedValue / 3),
> c(someDerivedValue + 4)
> {}
> };
>
> or introducing dedicated structure for passing construction parameters
> in, which is quite verbose.
>
> Introducing delegated constructors made much code less verbose.
> Introducing variables in member initializer list could make the next
> step to make it even neater.
>

It'd be enough if there were a way to re-enable aggregate initialization
(maybe with private access) in the presence of constructors; then we could
use an iife and named initialization:

class MyClass {
public:
     const int a, b, c;

     MyClass(int someBaseValue)
      : MyClass([&]
      {
          auto someDerivedValue = SomeHeavyOperation(someBaseValue);
          return MyClass{
              .a = someDerivedValue * 2,
              .b = someDerivedValue / 3,
              .c = someDerivedValue + 4,
          };
      }())
     {}
};

Received on 2021-09-01 04:58:06