Search code examples
c++templatesc++17variadic-templatesgeneric-programming

declare function pointer in templated class from template arguments


I am trying to declare function pointer from template argument of function prototype

template <typename ReturnType, typename... Args> class DllFunction {
public:
  ReturnType (*fptr_)(Args...);
};

DllFunction<int(int)> f;

but I get this error:

error: C2091: function returns function


Solution

  • You're mixing two different ways.

    Or you declare DllFunction receiving the return and the variadic list of argument types

    template <typename ReturnType, typename... Args> class DllFunction {
    public:
      ReturnType (*fptr_)(Args...);
    };
    

    but you have to avoid to call it with the form int(int) and you have to use

    // .........VVV  return type
    DllFunction<int, int> f;
    // ..............^^^  arguments types
    

    or you call using the form ReturnType(Args...) and you have to declare a DllFunction object as follows

    template <typename>
    class DllFunction;
    
    template <typename ReturnType, typename... Args>
    class DllFunction<ReturnType(Args...)> {
    public:
      ReturnType (*fptr_)(Args...);
    };
    

    You can also use the pointer function form

    template <typename>
    class DllFunction;
    
    template <typename ReturnType, typename... Args>
    class DllFunction<ReturnType(*)(Args...)> {
    public:
      ReturnType (*fptr_)(Args...);
    };
    

    so you can use decltype() for the template type

    int foo (int);
    
    DllFunction<decltype(&foo)> f;