Passing any function as template parameter

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 … Read more

How to pass a function pointer that points to constructor?

You cannot take the address of a constructor (C++98 Standard 12.1/12 Constructors – “12.1-12 Constructors – “The address of a constructor shall not be taken.”) Your best bet is to have a factory function/method that creates the Object and pass the address of the factory: class Object; class Class{ public: Class(const std::string &n, Object *(*c)()) … Read more

Why do we use std::function in C++ rather than the original C function pointer? [duplicate]

std::function can hold more than function pointers, namely functors. #include <functional> void foo(double){} struct foo_functor{ void operator()(float) const{} }; int main(){ std::function<void(int)> f1(foo), f2((foo_functor())); f1(5); f2(6); } Live example on Ideone. As the example shows, you also don’t need the exact same signature, as long as they are compatible (i.e., the parameter type of std::function … Read more

How do I get the argument types of a function pointer in a variadic template class?

You can write function_traits class as shown below, to discover the argument types, return type, and number of arguments: template<typename T> struct function_traits; template<typename R, typename …Args> struct function_traits<std::function<R(Args…)>> { static const size_t nargs = sizeof…(Args); typedef R result_type; template <size_t i> struct arg { typedef typename std::tuple_element<i, std::tuple<Args…>>::type type; }; }; Test code: struct … Read more

convert std::bind to function pointer

Is there any way I can pass the member to the function? Unless your class object is some kind of global object – it is not possible. Because objects may contain some data, while function pointer is just pointer to function – it doesn’t contain any runtime context, only compile-time one. If you accept having … Read more

Using a STL map of function pointers

Whatever your function signatures are: typedef void (*ScriptFunction)(void); // function pointer type typedef std::unordered_map<std::string, ScriptFunction> script_map; // … void some_function() { } // … script_map m; m.emplace(“blah”, &some_function); // … void call_script(const std::string& pFunction) { auto iter = m.find(pFunction); if (iter == m.end()) { // not found } (*iter->second)(); } Note that the ScriptFunction type … Read more