Is There a way to use the Parameter Names from a typedef

一曲冷凌霜 提交于 2019-12-31 05:42:47

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!