简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM