How to initialize an array of template size?

I want to initialize an array of template sizes without default constructors, as shown in the following code:

#include <array> template<std::size_t N> class Foo { public: class Bar { Foo<N> & _super; public: Bar(Foo<N> *super) : _super(*super) { } }; std::array<Bar, N> _array; Foo(void) : _array{{}} // We need {this, ...} N times { } }; int main(void) { Foo<3> foo; (void)foo; return 0; } 

Can I say: "I want an array of N objects, all initialized using the same parameter"? I think there is a way of meta-programming templates, but I cannot figure out how to do this.

+5
source share
2 answers

You can simply add one this at a time until you have N of them, after which you simply initialize _array :

  Foo() : Foo(this) { } private: template <class... T, std::enable_if_t<(sizeof...(T) < N), void*> = nullptr> Foo(T... args) : Foo(args..., this) { } template <class... T, std::enable_if_t<(sizeof...(T) == N), void*> = nullptr> Foo(T... args) : _array{{args...}} { } 
+2
source

Anything is possible with a little help from make_index_sequence :

  Foo() : Foo(std::make_index_sequence<N>()) {} template <size_t... I> Foo(std::index_sequence<I...> ) : _array{((void)I, this)...} {} 

Note the comma operator (,) in the _array constructor - courtesy of @Quentin (as opposed to calling the function).

+9
source

Source: https://habr.com/ru/post/1247876/


All Articles