O
O
old2ev2020-11-07 16:48:48
C++ / C#
old2ev, 2020-11-07 16:48:48

Is it possible in C++ to pass the size of an init-list aka std::initializer_list::size() to a class template parameter of type unsigned long via a constructor?

There is a class like this:

template <size_t size>
class A {
    Any_Type array[size];
public:
    //Тут может быть какой-либо шаблон...
    A(std::initializer_list<Any_Type> init_list) -> A</*Тут должен быть параметр для CTDA*/> {
       //Инициализация массива array данными из init_list
    }

};


As a result, it should work in this way:
A a = {...};
That is, without explicitly specifying the size of the type.
What I already tried:
// Самый тупой вариант
A(std::initializer_list<Any_Type> init_list) -> A<init_list.size()> // Нет ибо init_list не существует во время компиляции и даже constexpr тут не поможет

A(std::initializer_list<Any_Type> init_list) -> A<std::initializer_list<Any_Type>::size()> // Разумеется потому что size не статик ф-ция

template<size_t count_elem>
A(Any_Type const (&arr)[count_elem]) -> StaticByteArray<count_elem> // Nope...

template<size_t count_elem>
A(Any_Type const (&arr)[count_elem]) -> StaticByteArray<sizeof (arr)> // Nope...

// Да это точно не вариант, ибо шаблон будет хватать любой мусор, но всё же...
template<typename T>
A(T arr) -> StaticByteArray<sizeof (arr)> // Хз почему но нет...


Has anyone worked with this?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
A
Anton Zhilin, 2020-11-07
@old2ev

template <size_t N>
class ArrayWrapper {
  MyType data_[N];

public:
  explicit ArrayWrapper(MyType (&&arr)[N]) : data_(std::move(arr)) {}
};

template <size_t N>
ArrayWrapper(MyType (&&arr)[N]) -> ArrayWrapper<N>;

A
Alexander Ananiev, 2020-11-07
@SaNNy32

Why not do so?

template <class T>
class A {
   std::vector<T> array;
public:  
   A(std::initializer_list<T> init_list): array(init_list)
   {
   }
};

M
maaGames, 2020-11-07
@maaGames

So "A a = {...};" it will definitely not work, because you need to specify the type of the template parameter. Those. in the record "A a" the type is underdefined.
Perhaps you can make an analogue of std::make_shared, which will return, for example, A<5>. Something like:

template< int Size>
A<Size> make_A( std::initializer_list<T> init_list )
{
      A<init_list .size()> a( init_list ); // size() - constexpr
      return a;
}

auto a = make_A( {...} );

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question