2
class Y; //not really relevant

class B
{
  B(Y*);
  //stuff
}

template<int SIZE> class X : public Y
{
  B array[SIZE];

  X();
}

I would like to call constructor of each element of array[] with this as parameter. How can I do that in pretty way? C++14 and even 17 are OK for me.

2 Answers 2

4

One of several approaches:

template <int SIZE>
class X : public Y
{
    B array[SIZE];

    template <std::size_t>
    X* that() { return this; } // don't abuse the comma operator

    template <std::size_t... Is>
    X(std::index_sequence<Is...>) : array{ that<Is>()... } {}

public:
    X() : X(std::make_index_sequence<SIZE>{}) {}
};

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

What is std::make_index_sequence and std::index_sequence? I can't find any docs for that but I've found an information somewhere that those are [std::integer_sequence`](en.cppreference.com/w/cpp/utility/integer_sequence) aliases...
2

There's no "nice" or simple way of doing it with C arrays (or even std::array).

You can to it very easily if you change to use a std::vector instead. It has a constructor that allows you to set the size and pass the default value for all elements:

template<int SIZE> class X : public Y
{
    std::vector<B> array;

    X()
        : array(SIZE, B(this))
    {}
};

5 Comments

What a shame. I REALLY hate C++, but it's fast so I have to live with it... You could call it marriage of convenience -.-
@psorek Why are you saying "what a shame"? In C++, you want to avoid arrays anyway whenever possible. To me, he solution of Joachim Pileborg sounds pretty much what you should want.
I would very much like to avoid dynamic memory allocation as much as possible, becouse of reasons.
@psorek "Because of reasons" is really no explanation. "Because of a limited heap on an embedded system" is a good reason and explanation.
This will copy-construct each vector element from a temporary B(this), not clear if this suits OP's requirements

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.