Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template parameter pack attribute

We have template class:

template<int i>
class A
{
...
};

But how to declare packer of template classes:

template<int... is>
Pack
{

private:
    A<is...> attrs;
};

Or howto have collection of classes A?

like image 267
janulo Avatar asked Oct 23 '16 14:10

janulo


2 Answers

Using std::tuple, by example

#include <tuple>

template <int i>
class A
 { };

template <int... is>
class Pack
 { std::tuple<A<is>...>  attrs; };

int main()
 {
   Pack<2,3,5,7,11,13>  p;
 }

Another way can be through inheritance

template <int i>
class A
 { };

template <int... is>
class Pack : A<is>...
 { };

int main()
 {
   Pack<2,3,5,7,11,13>  p;
 }
like image 181
max66 Avatar answered Oct 01 '22 23:10

max66


The best approach I know is to use a type list:

template<class...> struct type_list{};

template<int...Is>
using a_pack = type_list<A<Is>...>;

With type list, it is really easy to perform transformation or make operation on each members. For example let's create a type_list of std:vector with the previous code:

template<class> struct vectors_of;

template<class...As> struct vectors_of<type_list<As...>>{
     using type=type_list<std::vector<As>...>;
};
using vectors_of_a = typename vectors_of<a_pack<1,2>>::type;

Their is a lot of documentation about type lists. This is one of the basic tools of meta-programmers since this book: Modern C++ Design (which uses pre-c++11). With C++11, it is even easier to use it.

like image 25
Oliv Avatar answered Oct 01 '22 23:10

Oliv