Opsenas
Opsenas

Reputation: 722

Initializer list time member container initialization with array of members

I'm attempting to implement class member container initiallization using array of member variables example code:

//Pseudo container declaration
class CContainer
{
    template<size_t nSize>
    CContainer(CMember* acArray[nSize]);
};
//class whos members i wanna pass as array to container initialization
class CProblematic
{
    CMember m_1;
    CMember m_2;
    ...
    CMember m_n;
    CContainer m_cContainer;

    //constructor with container initialization
    CProblematic(int parameter)
    : m_1(parameter)
    , m_2(parameter)
    ...
    , m_n(parameter)
    , m_cContainer({&m_1, &m_2, ... , &m_n})
    {}
};

I've tried multiple container constructor syntax, but none seem to help, for example i tried to use CContainer(CMember** apcArray, size_t nSize and pass it during CProblematic construction, but non seem to help when using {...} style array creation, maybe someone could point me to my mistake or point toward solution?

I know that the easiest way to solve this is just simply add in constructor body m_cContainer.Add(&m_1) for each member, but i'm more interested is there a solution to initiallize this way...

Upvotes: 0

Views: 31

Answers (2)

T.C.
T.C.

Reputation: 137394

On a compiler implementing the resolution of CWG 1591, you can do

template<size_t nSize>
CContainer(CMember* const (&acArray)[nSize]); // or CMember* (&&acArray)[nSize]

And let nSize be deduced from the braced-init-list {&m_1, &m_2, ... , &m_n}.

Otherwise, to deduce the bound, you can use std::array with a helper function template. The following is a simplified version of std::experimental::make_array:

template <class... Ts>
auto make_array(Ts&&... t) -> std::array<std::common_type_t<Ts...>, sizeof...(Ts)>{
    return { std::forward<Ts>(t)... };
}

Then do m_cContainer(make_array(&m_1, &m_2, ... , &m_n)) with a constructor taking a std::array like in your answer:

template<size_t nSize>
CContainer(std::array<CMember*, nSize>&& aArray) 

Upvotes: 1

Opsenas
Opsenas

Reputation: 722

seems that found a solution, if someone stumbles to same problem, here's my solution

//problematic constructor 
CProblematic(int parameter)
    : m_1(parameter)
    , m_2(parameter)
    ...
    , m_n(parameter)
    //only drawback, you must specify n by hand
    , m_cContainer(std::array<CMember*, n>{&m_1, &m_2, ... , &m_n})
    {}

//Container constructor
template<size_t nSize>
CContainer(std::array<CMember*, nSize>&& aArray) 
//since we're creating rvalue reference in initialization list

Upvotes: 1

Related Questions