简体   繁体   中英

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:

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

Now I want to write another function that takes the function f as an argument. 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. Hope anyone can help me. Thank you very much!

You can emulate that with a callable 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. But I suggest you make the template argument a regular argument so you don't need stuff like this.

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