Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide empty base class for aggregate initialization

Consider the following code:

struct A
{
    // No data members
    //...
};

template<typename T, size_t N>
struct B : A
{
    T data[N];
}

This is how you have to initialize B: B<int, 3> b = { {}, {1, 2, 3} }; I want to avoid the unnecessary empty {} for the base class. There is a solution proposed by Jarod42 here, however, it doesn't work with elements default initialization: B<int, 3> b = {1, 2, 3}; is fine but B<int, 3> b = {1}; is not: b.data[1] and b.data[2] aren't default initialized to 0, and a compiler error occurs. Is there any way (or there will be with c++20) to "hide" base class from construction?

like image 880
user7769147 Avatar asked Dec 27 '19 09:12

user7769147


4 Answers

The easiest solution is to add a variadic constructor:

struct A { };

template<typename T, std::size_t N>
struct B : A {
    template<class... Ts, typename = std::enable_if_t<
        (std::is_convertible_v<Ts, T> && ...)>>
    B(Ts&&... args) : data{std::forward<Ts>(args)...} {}

    T data[N];
};

void foo() {
    B<int, 3> b1 = {1, 2, 3};
    B<int, 3> b2 = {1};
}

If you provide fewer elements in the {...} initializer list than N, the remaining elements in the array data will be value-initialized as by T().

like image 190
Evg Avatar answered Nov 19 '22 12:11

Evg


Since C++20 you could use designated initializers in aggregate initialization.

B<int, 3> b = { .data {1} }; // initialize b.data with {1}, 
                             // b.data[0] is 1, b.data[1] and b.data[2] would be 0
like image 26
songyuanyao Avatar answered Nov 19 '22 12:11

songyuanyao


Still with constructor, you might do something like:

template<typename T, size_t N>
struct B : A
{
public:
    constexpr B() : data{} {}

    template <typename ... Ts,
              std::enable_if_t<(sizeof...(Ts) != 0 && sizeof...(Ts) < N)
                               || !std::is_same_v<B, std::decay_t<T>>, int> = 0>
    constexpr B(T&& arg, Ts&&... args) : data{std::forward<T>(arg), std::forward<Ts>(args)...}
    {}

    T data[N];
};

Demo

SFINAE is done mainly to avoid to create pseudo copy constructor B(B&).

You would need extra private tag to support B<std::index_sequence<0, 1>, 42> ;-)

like image 4
Jarod42 Avatar answered Nov 19 '22 12:11

Jarod42


I've found another solution that (I don't know how) works perfectly and solves the problem we were discussing under Evg's answer

struct A {};

template<typename T, size_t N>
struct B_data
{
    T data[N];
};

template<typename T, size_t N>
struct B : B_data<T, N>, A
{
    // ...
};
like image 2
user7769147 Avatar answered Nov 19 '22 11:11

user7769147