Initialization of a member variable tuple

410 views Asked by At

I have the following code:

struct A
{
    const string name;

    A(string name) :name(name) {}
};

struct Parent 
{
public:
    const decltype(make_tuple(A("AA"))) children{ make_tuple(A("AA")) };

    Parent()
    {

    }

};

Is it possible to avoid typing A("AA") twice?

Like when you use the auto keyword- but working.

1

There are 1 answers

0
Daniel Frey On BEST ANSWER

You can move A("AA") or even better make_tuple(A("AA")) into its own function:

namespace {
    auto make_children() { return make_tuple(A("AA")); }
}

struct Parent 
{    
public:
    const decltype(make_children()) children{ make_children() };

    Parent()
    {

    }

};

Live example

That way you only need to repeat the name of the helper function twice. Depending on the size/complexity of the expression in your real code, that might be a win.