Passing any function as template parameter

自作多情 提交于 2019-12-02 17:29:17

I believe shortening this is currently impossible. A year ago, the C++ committee looked at http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2013/n3601.html to fix this, and they encouraged the authors to pursue it further after C++14 was released.

It's now possible in C++17 with template<auto>:

template<auto Func>
struct FuncWrapper final
{
    template<typename... Args>
    auto operator()(Args &&... args) const
    {
        return Func(std::forward<Args>(args)...);
    }
};

int add(int a, int b)
{
    return a + b;
}

int main()
{
    FuncWrapper<add> wrapper;
    return wrapper(12, 34);
}

Demo: https://godbolt.org/g/B7W56t

You can use #ifdef __cpp_nontype_template_parameter_auto to detect compiler support for this in your code.

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

typedef int (*MyFunctionType)(int);

template <typename FunctionTypedef, typename ReturnType, typename ParameterType>
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<MyFunctionType, int, int>(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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!