Passing any function as template parameter

前端 未结 3 1705
天涯浪人
天涯浪人 2021-01-31 03:10

I want to pass a function value as a template parameter to a function. Currently the best I managed to do is :

template< typename F, F f >         


        
3条回答
  •  说谎
    说谎 (楼主)
    2021-01-31 03:40

    You need to make a typedef for whatever function type you want to pass as a pointer, like this:

    typedef int (*MyFunctionType)(int);
    
    template 
    ReturnType callFunction(FunctionTypedef functionPointer, ParameterType i)
    {
      static MyFunctionType myFunctionPointer = functionPointer;
      return (*functionPointer)(i);
    }
    int myFunction(int i)
    {
    }
    
    
    int main()
    {
      int i = 7;
      MyFunctionType myFunctionPointer = myFunction;
      return callFunction(myFunctionPointer, i);
    }
    

    Edit: If you want to store these arbitrarily typed function pointers, then make a base class with a virtual "call function" function, and a templated derived class that implements this function.

提交回复
热议问题