mkmostafa
mkmostafa

Reputation: 3171

Nested template parameters for functions

template <typename T> class foo2 {
};

Sample 1

template <typename T, template <typename> class foo2>
foo2<T> func2(){
}

Sample 2

template <template <typename T> class foo2>
foo2<T> func2(){
}

I have a template class and I would like to write a function that accepts only that class (with any of it's templates of course) why does sample 1 works and 2 does not?

Edit:

Please provide an explanation of how the matching happens? Clearly the function in sample 1 takes two template parameters without any default values, however in the call in the main only one parameter is provided.

Edit2: I want another func2 overload for the templated foo2 class, I already have defined in my code.

template <typename T>
T func2(){
}

Upvotes: 1

Views: 2546

Answers (1)

Andrew
Andrew

Reputation: 5352

Template template parameters define a template name in the body of the function. You have to provide the parameter to instantiate them. This means that the T in

template <template <typename T> class foo2> void func2(foo2<T>);

is not visible elsewhere; only the template name foo2 is.

Your first sample,

template <typename T, template <typename> class foo2> void func2(foo2<T>);

works because the T is a top-level template type parameter, which is

  1. visible to the function body, and
  2. deduced from the function argument.

However, this use case is more easily written with a simple template type parameter and direct use of the class foo2:

template <typename T> void func2(foo2<T>);

See, for example, template parameters and template arguments on cppreference for details


Note, the question was edited after I wrote the above, and the type is no longer used as a function argument. The point about type deduction no longer applies, but the rest of the answer stands.

Upvotes: 4

Related Questions