Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ template with partially fixed argument list

Consider a case like the following:

template<typename T>
class A { ... };

template<typename T, typename DataType = std::vector<A<T>>>
class B {
  ....
  DataType data;
  ...
}

In my case the DataType type can be any std "container", but it must always be specialized with type A. The use of A should be transparent from outside class B, however in the definition of B without the default type for DataType one should explicitly specify e.g. B<int, std::deque<A<int>>. I'd like to remove this possibility and achieve something like:

template<typename T, typename container = std::vector>
class B{
  using DataType = container<A<T>>;
  ...
}

so that I would specialize B like B<int, std::vector>. Of course it cannot be exactly like this because container in this case should a complete type and then must be specialized. Is there a way to achieve this with c++14?

like image 445
Nicola Lissandrini Avatar asked Nov 01 '25 17:11

Nicola Lissandrini


1 Answers

You can do it with template template parameter, e.g.

template<typename T, template <typename...> typename container = std::vector>
class B {
  using DataType = container<A<T>>;
  ...
};

Then use it like B<int> (i.e. B<int, std::vector>) or B<int, std::deque>.

like image 136
songyuanyao Avatar answered Nov 04 '25 06:11

songyuanyao