有没有办法使用 typedef 中的参数名称 [英] Is There a way to use the Parameter Names from a typedef

查看:28
本文介绍了有没有办法使用 typedef 中的参数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以给定一个 typedef 定义一个函数指针,参数名称如下:

So given a typedef that defines a function pointer with parameter names like this:

typedef void(*FOO)(const int arg);

有没有办法可以只使用这个函数指针来定义我的函数的签名?显然这行不通,但我想以某种方式使用 typedef 来指定具有相应类型的函数签名:

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:

错误:arg 未在此范围内声明

error: arg was not declared in this scope

推荐答案

您尝试执行的操作无效.FOOvoid(*)(const int) 的别名.所以

What you are trying to do will not work. FOO is an alias for void(*)(const int). so

FOO foo {
    cout << arg << endl;
}

变成

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);
}

这篇关于有没有办法使用 typedef 中的参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆