Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert initializer_list<T> to initializer_list<vector<T>> at compile time

I have a class constructor that accepts an

initializer_list<T>

this constructor has to run the parent class constructor that accepts an

initializer_list<vector<T>>.

so I have to convert the initializer list to an 2d initializer list.

{1, 2, 3, 4} to { {1}, {2}, {3}, {4} }

EDIT:

I have a class constructor that accepts an

initializer_list<T>

this constructor has to run the parent class constructor that accepts an

initializer_list<array<T, 1>>.

so I have to convert the initializer list to an 2d initializer list.

{1, 2, 3, 4} to { {1}, {2}, {3}, {4} }
like image 852
user2798943 Avatar asked Mar 19 '23 16:03

user2798943


2 Answers

Why not have your child class take parameter pack and forward it off to the parent constructor?

struct Parent
{
    template<typename T>
    Parent(std::initializer_list<std::array<T, 1>>) { }

    virtual ~Parent() = default;
};

struct Child : Parent
{
    template<class... Args>
    Child(Args&&... args) : Parent{{{args}...}} { }
};
like image 154
David G Avatar answered Apr 09 '23 00:04

David G


Below you can find a complete example if you are still having troubles with mixing <typename T> from class' declaration with <typename... Args> pack within constructor:

#include <iostream>
#include <array>
#include <utility>
#include <initializer_list>

template <typename T>
class A
{
public:
    A(std::initializer_list<std::array<T, 1>> i);

    virtual ~A() = default;
};

template <typename T>
A<T>::A(std::initializer_list<std::array<T, 1>> i)
{
    std::cout << i.size() << std::endl;
}

template <typename T>
class B : public A<T>
{
public:
    template <typename... Args>
    B(Args&&... args);
};

template <typename T>
template <typename... Args>
B<T>::B(Args&&... args) : A<T>{std::array<T, 1>{std::forward<Args>(args)}...}
{

}

int main()
{
    B<int> b{ 1, 2, 3, 4, 5, 6, 7 };
    return 0;
}

Live demo link.

like image 28
Piotr Skotnicki Avatar answered Apr 09 '23 00:04

Piotr Skotnicki