Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using function template as template template parameter in C++

Suppose I have a function with a template template parameter, like this:

template <template <class T> class F, typename P>
void applyFunction(int param)
{
    F<P> fn;
    fn(param);
}

The above can take an arbitrary class template for a Functor and apply it. So for example if I defined:

template<typename T>
struct SomeFunctor
{
    void operator()(int param)
    {
        T::doStuff(param);
    }
};

Then I could make the following call:

applyFunction<SomeFunctor, MyClass>(0);

But what I'd really like to do is to be able to pass function templates (rather than just class templates that define functors). So if I had something like this:

template<typename T>
void someFunction(int param)
{
    T::doStuff(param);
}

Ideally I'd be able to do something like this:

applyFunction<someFunction, MyClass>(0);

Unfortunately as it stands this is not legal C++. Is there a way to do this that I'm missing? In other words pass a function template rather than a class template as a template template parameter? Conceptually I don't see why it shouldn't be possible.

like image 820
Smeeheey Avatar asked May 05 '16 11:05

Smeeheey


People also ask

Can a template be a template parameter?

Templates can be template parameters. In this case, they are called template parameters. The container adaptors std::stack, std::queue, and std::priority_queue use per default a std::deque to hold their arguments, but you can use a different container.

Can a template parameter be a function?

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.

Why do we use template template parameter?

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

Which is correct example of template parameters?

For example, given a specialization Stack<int>, “int” is a template argument. Instantiation: This is when the compiler generates a regular class, method, or function by substituting each of the template's parameters with a concrete type.


1 Answers

You could take a pointer to your function as template argument:

template < typename T, T (*F)(int) >
void apply_function(int param) {
    F(param);
}

template < typename T >
T some_function(int param) {
    T::doStuff(param);
}    

int main() {
    apply_function< float, some_function >(5);
}

In your case it would be:

apply_function< MyClass, some_function >(0);

then for example.

like image 70
tobspr Avatar answered Oct 17 '22 02:10

tobspr