问题
So given a typedef
that defines a function pointer with parameter names like this:
typedef void(*FOO)(const int arg);
Is there a way that I can just use this function pointer to define the signature of my function? Obviously this won't work, but I'd like to somehow use the typedef
to specify a function signature with a corresponding type:
FOO foo {
cout << arg << endl;
}
Again, I know this doesn't work, and is bad syntax. It will just give the error:
error:
arg
was not declared in this scope
回答1:
What you are trying to do will not work. FOO
is an alias for void(*)(const int)
. so
FOO foo {
cout << arg << endl;
}
becomes
void(*)(const int) foo {
cout << arg << endl;
}
and that just doesn't work. What you can do though is define a macro that takes a name and use that to stamp out a function signature. That would look like
#define MAKE_FUNCTION(NAME) void NAME(const int arg)
MAKE_FUNCTION(foo){ std::cout << arg * 5 << "\n"; }
MAKE_FUNCTION(bar){ std::cout << arg * 10 << "\n"; }
int main()
{
foo(1);
bar(2);
}
回答2:
The definition of a function pointer has nothing to do with the declaration nor the definition of a function so the answer is no.
来源:https://stackoverflow.com/questions/51405920/is-there-a-way-to-use-the-parameter-names-from-a-typedef