Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare template template parameter

Suppose I have two classes Foo1<T> and Foo2<T>.

I then want to create a function bar that takes a reference to a std::vector<Foo1<T>> or to a std::vector<Foo2<T>> but always returns a std::vector<Foo1<T>>:

template<class T, class Y> std::vector<Foo1<T>> bar(std::vector<Y<T>>&)

Sadly but the compiler doesn't like the <Y<T>> bit. One way round this is to provide two overloads but is there a way I can arrange the above so it's correct?

like image 746
P45 Imminent Avatar asked Mar 31 '16 16:03

P45 Imminent


People also ask

Can a template be a template parameter?

A template argument for a template template parameter is the name of a class template. When the compiler tries to find a template to match the template template argument, it only considers primary class templates. (A primary template is the template that is being specialized.)

What is a template template parameter in C++?

In C++ this can be achieved using template parameters. A template parameter is a special kind of parameter that can be used to pass a type as argument: just like regular function parameters can be used to pass values to a function, template parameters allow to pass also types to a function.

How do you declare a template function?

To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>( float original ); Template arguments may be omitted when the compiler can infer them.

Why do we use template template parameter?

8. Why we use :: template-template parameter? Explanation: It is used to adapt a policy into binary ones.


1 Answers

You need template template parameter:

template<class T, template <typename> class Y> 
std::vector<Foo1<T>> bar(std::vector<Y<T>>&) {}
like image 168
songyuanyao Avatar answered Sep 20 '22 01:09

songyuanyao