Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting argument count of a function pointer

Tags:

c++

c++11

I'm now using 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 kinda ugly and limited (the user can't call argc with a function with any number of arguments.) Is there a better way to do it?

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

like image 868
Guilherme Bernal Avatar asked Dec 27 '11 13:12

Guilherme Bernal


People also ask

How do you indicate the parameters to a function pointer?

In the above syntax, the type is the variable type which is returned by the function, *pointer_name is the function pointer, and the parameter is the list of the argument passed to the function. Let's consider an example: float (*add)(); // this is a legal declaration for the function pointer.

What is the correct syntax to pass a function pointer as an argument?

Which of the following is a correct syntax to pass a Function Pointer as an argument? Explanation: None.

What is a pointer argument?

Pointers as Function Argument in C Pointer as a function parameter is used to hold addresses of arguments passed during function call. This is also known as call by reference. When a function is called by reference any change made to the reference variable will effect the original variable.

What is the difference between function pointer and pointer to function?

A function pointer is a pointer that either has an indeterminate value, or has a null pointer value, or points to a function. A pointer to a function is a pointer that points to a function. A function pointer is a pointer that either has an indeterminate value, or has a null pointer value, or points to a function.


1 Answers

Cleaner version of @Paolo's answer, usable with actual objects:

template<class R, class... Args>
constexpr unsigned arity(std::function<R(Args...)> const&){
  return sizeof...(Args);
}
like image 104
Xeo Avatar answered Sep 21 '22 18:09

Xeo