Search code examples
c++c++14decltype

Initialization of a member variable tuple


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.


Solution

  • 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.