How can I pass N number of generic arguments to a typedef function pointer?

89 views Asked by At

I have this typedef function pointer plot:

typedef void(*plot)();

How can I pass a generic argument to it (Something like this):

template<typename T>
typedef void(*plot)(T);

And then, how can I pass N number of generic arguments to it?

template<typename T>
typedef void(*plot)(T ...);
2

There are 2 answers

0
CS Pei On BEST ANSWER

In C++11, you can do something like this

template<typename T>
using fun_ptr = void (*)(T);

And for the second case,

template<typename... T>
using fun_ptr = void (*)(T ...);
0
Ericson Willians On

It's possible using a combination of Variadic Templates and Type Aliases as follows:

template<typename... T>
using ptr = void (*)(T ...);

Example:

template<typename... T>
using ptr = void (*)(T ...);

void f(int n, string s, float x)
{
    cout << n << s << x;
}

int main(int argc, char **argv)
{
    ptr<int, string, float> x; // Arbitrary number of template arguments of arbitrary types.
    x = f;
    x(7, " nasty function pointer ", 3.4);

    return 0;
}

Observation: If the ellipsis is omitted after the typename, like so:

template<typename T>
using ptr = void (*)(T ...);

The compiler raises a "wrong number of template arguments (3, should be 1)" error, considering the aforementioned example.