简体   繁体   English

在C ++中使用函数模板作为模板模板参数

[英]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. 以上内容可以为Functor采用任意类模板并应用它。 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++. 不幸的是,这不是合法的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. 然后例如。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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