Search code examples
c++c++11templatesfunction-pointersfunction-templates

How to template a parameter in function pointer?


I have a template:

template<typename T>
void testFuction(int(*testFunc)(CallBack, void *, T *))
{
    // define CallBack callback, void* param1, T* param2
    // ...
    testFunc(callback, param1, param2);
}

It works but it looks terrible, I want to do something like:

template<typename T>
// using TestFunc<T> = std::function<int(CallBack, void *, T *)>
void testFuction(TestFunc<T> testFunc)
{
   // define CallBack callback, void* param1, T* param2
   // ...
   testFunc(callback, param1, param2);
}

But it doesn't work.

Can somebody help me with it? I also overload many similar functions like that with some added parameters and they look ugly. I want to define TestFunc<T> once and use it again in the template functions.


Solution

  • You can provide a type alias for the templated function pointer as follows

    #include <utility> // std::forward
    
    template<typename T>
    using FunPointerT = int(*)(CallBack, void*, T*);
    
    template<typename T, typename... Args>
    void testFuction(FunPointerT<T> funcPtr, Args&& ...args)
    {
       // variadic args, in the case of passing args to testFuction
       funcPtr(std::forward<Arg>(args)...);
    }
    

    Update as per Op's requirement

    template<typename T> 
    void testFuction(FunPointerT<T> funcPtr) 
    {
       // ...
       funcPtr(/* args from local function scope */);
    }