2

Is there a way to get the (MSVC) compiler to generate the following ctor' following the initializer list pattern pattern below which takes arguments in order of member deceleration instead of (or as well as) the default constructor ?

struct Foo{
    float a;
    float b;
    float c;

    Foo(float _a, float _b, float _c) : a(_a), b(_b), c(_c) {}
};
Barry
  • 286,269
  • 29
  • 621
  • 977
Saharsh Bishnoi
  • 341
  • 2
  • 10

2 Answers2

5

It already does, because your example is a POD aggregate type.

struct Foo{
    float a;
    float b;
    float c;
};

So you can initialize a Foo with something like

Foo f{1.0f, 2.0f, 3.0f};

Which is the same syntax as your manually defined constructor

Working demo

Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
  • Am I correct in thinking that syntactically its different ? Foo{...} instead of Foo(...), but close enough I guess. Maybe its too much to ask from the standard or the compiler, perhaps its more of a nicety that an IDE or plugin may be able to generate so there is less typing involved. – Saharsh Bishnoi Aug 06 '15 at 17:27
  • 1
    @SaharshBishnoi https://programmers.stackexchange.com/questions/133688/is-c11-uniform-initialization-a-replacement-for-the-old-style-syntax – Cory Kramer Aug 06 '15 at 17:29
0

You may use std::tuple

struct Foo : private std::tuple<float, float, float>{
    using std::tuple<float, float, float>::tuple;

    const float& a() const {std::get<0>(*this);}
    float& a() {std::get<0>(*this);}
    const float& b() const {std::get<1>(*this);}
    float& b() {std::get<1>(*this);}
    const float& c() const {std::get<2>(*this);}
    float& c() {std::get<2>(*this);}
};

but I think it is worst than writing constructor.

Jarod42
  • 203,559
  • 14
  • 181
  • 302