简体   繁体   English

在 C++ 中将 function 模板作为 function 参数传递

[英]Passing a function template as a function argument in C++

Suppose I have a template function that takes an integer as the template argument as follows:假设我有一个模板 function 以 integer 作为模板参数,如下所示:

template <int i> void f(int x) {...}

Now I want to write another function that takes the function f as an argument.现在我想写另一个 function 以 function f作为参数。 However I do not know how to achieve this.但是我不知道如何实现这一点。 For example, consider the following wrong code (that can not be compiled):例如,考虑以下错误代码(无法编译):

template <template <int> typename T> void g(T fun, int i, int x) {
    if (i == 0) fun<0>(x);
    else if (i == 1) fun<1>(x);
    //...
}

I have searched Google but It seems that all related questions are to pass a standard function as a template argument which is not the case here.我搜索了谷歌,但似乎所有相关问题都是通过标准 function 作为模板参数,但这里不是这种情况。 Hope anyone can help me.希望任何人都可以帮助我。 Thank you very much!非常感谢!

You can emulate that with a callable class:您可以使用可调用的 class 来模拟它:

template <int i>
struct f {
  void operator()(int x) {
    // ...
  }
};

template <template <int> typename T>
void g(int i, int x) {
  if (i == 0)
    T<0>{}(x);
  else if (i == 1)
    T<1>{}(x);
  //...
}

int main() { 
  g<f>(10, 12); 
}

Could also do the same with a named static method.也可以对命名的 static 方法执行相同的操作。 But I suggest you make the template argument a regular argument so you don't need stuff like this.但我建议你将模板参数设为常规参数,这样你就不需要这样的东西了。

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

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