Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass a function template as a template argument?

Let's asssume, that we have a template funcion:

template<typename T1, typename T2, typename T3>
T3 such_fun(T1 a, T2 b) {
    // do something...
}

and now we want to use it as an argument in another template, e.g. like that

template<typename T1, template<typename, typename, typename> some_function>
void big_fun(T1 a) {
   // some code...
   a = some_function<T1, T1, T1>(a, a);
   // some code...
}

Is it possible?

I know that I can use a struct with defined () operator. I'm just curious about functions.

EDIT:

While I was writing that question my friend found a partial solution:

template<typename T1, T1 (*some_function)(T1, T1)>
void big_fun(T1 a) {
   // some code...
   a = some_function(a, a);
   // some code...
}

But still - I'm curious if it's possible without a materialization of a function type before call. For example - I may want to call the passed template with various types combinations:

template<typename T1, typename T2, template<typename, typename, typename> some_function>
void big_fun(T1 a, T2 b) {
   // some code...
   a = some_function<T1, T1, T1>(a, a);
   a = some_function<T1, T2, T1>(a, b);
   b = some_function<T2, T2, T2>(b, b);
   b = some_function<T2, T1, T2>(b, a);
   // some code...
}
like image 631
Wojciech Żółtak Avatar asked Feb 24 '12 17:02

Wojciech Żółtak


1 Answers

No, this is not possible. From 14.3.3 in N3337:

A template-argument for a template template-parameter shall be the name of a class template or an alias template, expressed as id-expression . When the template-argument names a class template, only primary class templates are considered when matching the template template argument with the corresponding parameter; partial specializations are not considered even if their parameter lists match that of the template template parameter.

The first paragraph only mentions class templates explicitly. I guess it's also not really worth the trouble given that you can do something very similar already with functions or a std::function as an argument.

like image 163
pmr Avatar answered Sep 20 '22 05:09

pmr