Logo Questions Linux Laravel Mysql Ubuntu Git Menu

Why can't I declare a type with both template container and template contained value?




Why isn't this valid C++?

template <typename Container, typename T>
foo (const Container <T> &);

g++ gives me Container is not a template which is clearly not what it really means.

Trying template <typename Container> template <typename T> doesn't work either, neither does const typename Container <T> &

It seems reasonable to me that one would want to define an interface which is generic over both the container and the contained type.


  • in terms of standards, why isn't this allowed?
  • in terms of designing standards, why wouldn't this be allowed, would it cause problems?
  • is there a workaround in C++14, other than basing the interface on iterators?
like image 463
spraff Avatar asked Mar 09 '16 14:03


1 Answers

You can do this:

template <template <class... > class Container, class T>
bool foo (const Container<T> &);

This syntax (class...) tells the compiler that container is a template with any number of arguments.

Remember, when you have template <class T> you want T to be the type. std::vector is not a type, it is a template. std::vector<int> is a type, but that is not a template, so you can't have std::vector<int> <char>.

like image 130
SergeyA Avatar answered Nov 04 '22 04:11