Home > Enterprise >  c template with partially fixed argument list
c template with partially fixed argument list

Time:02-08

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?

CodePudding user response:

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>.

  •  Tags:  
  • Related