Compile time array from C ++ template package

How can I create, for example, std :: array from a package of template parameters during compilation?

This shows what I need, but without a parameter package.

template<typename T1, typename T2, typename T3> struct ToInfoArray { static constexpr std::array<Info, 3> value = { { T1::info, T2::info, T3::info } }; }; 

Live Demonstration of Intended Use

Bonus question: Do you use std::array , array[] or std::initializer_list as a type for InfoArray?

+5
source share
2 answers
 template <typename... Ts> struct ToInfoArray { static constexpr std::array<Info, sizeof...(Ts)> value = { { Ts::info... } }; }; 

Demo

Do you use std :: array, array [] or std :: initializer_list as a type for InfoArray?

std::array<T,N> . This is a collection that behaves (with comparable performance) in the same way as a regular array, but provides an additional interface for working with its elements; he himself is a copied type.

std::initializer_list is not here for many reasons. When it is used as a data element (with an initializer in the class), stored elements become invalid after the execution of any of the constructors. It is not guaranteed to be a literal type, so it cannot be marked as constexpr . Its size is not used (available) in constant expressions. It does not provide random access logic (without resorting to pointer arithmetic); the only way to list its elements is to iterate from begin() to end() , which, in addition, gives pointers to constant elements. std::initializer_list was intended to be serviced primarily as a function parameter.

+7
source

With C ++ 14, you can simply make it a variable template:

 template <typename... Ts> constexpr std::array<Info, sizeof...(Ts)> value{{Ts::info...}}; 

Otherwise, the correct syntax for your use is:

 template <typename... Ts> struct ToInfoArray { static constexpr std::array<Info, sizeof...(Ts)> value{{Ts::info...}}; }; 

And strongly prefer std::array<> for raw arrays or initializer_list .

+3
source

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


All Articles