Getting the number of arguments to a function pointer

Now I use this code:

size_t argc(std::function<Foo()>) { return 0; } size_t argc(std::function<Foo(Bar)>) { return 1; } size_t argc(std::function<Foo(Bar, Bar)>) { return 2; } size_t argc(std::function<Foo(Bar, Bar, Bar)>) { return 3; } // ... 

But it is rather ugly and limited (the user cannot call argc with a function with any number of arguments.) Is there a better way to do this?

Note: return type and argument type are always the same. I know that I can use patterns to accept any type, but I don't need this.

+8
c ++ c ++ 11
source share
2 answers

A cleaner version of @Paolo's answer, suitable for use with real objects:

 template<class R, class... Args> constexpr unsigned arity(std::function<R(Args...)> const&){ return sizeof...(Args); } 
+12
source share

The following actions will work for any arity, but accept arbitrary argument types:

 template <typename T> struct arity { }; template <typename... Args> struct arity<std::function<Foo(Args...)>> { static const int value = sizeof...(Args); }; 

If you really want to limit the argument type to functions like Foo(Bar, Bar, ...) , you can do something like this:

 template <typename T> struct arity { }; template <typename... Args> struct const_tuple { }; template <> struct const_tuple<> { struct unsupported_function_type { }; }; template <typename... Args> struct const_tuple<Bar, Args...> { typedef typename const_tuple<Args...>::unsupported_function_type unsupported_function_type; }; template <typename... Args> struct arity<std::function<Foo(Args...)>> : public const_tuple<Args...>::unsupported_function_type { static const int value = sizeof...(Args); }; 

This will give you a compilation error whenever arity is called with an unsupported function type.

+5
source share

All Articles