c++ - 有没有办法使用 typedef 中的参数名称

标签 c++ parameters arguments function-pointers typedef

因此,给定一个 typedef,它定义了一个具有如下参数名称的函数指针:

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

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

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

同样,我知道这行不通,而且是错误的语法。它只会给出错误:

error: arg was not declared in this scope

最佳答案

您尝试执行的操作不会奏效。 FOOvoid(*)(const int) 的别名。所以

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

成为

void(*)(const int) foo {
    cout << arg << endl;
}   

那是行不通的。不过,您可以做的是定义一个带有名称的宏,并使用它来消除函数签名。看起来像

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

关于c++ - 有没有办法使用 typedef 中的参数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51405920/

相关文章:

c++ - 泛化返回基于对象和类方法的可调用函数的函数

c++ - pthreads 不能从 main() 函数访问变量吗?

c++ - 如果我们不等待就发出信号量会发生什么?

typescript - Vue + Typescript vue-router 和参数类型

java - 具有许多参数的枚举

python - 检查数字 Python 代码中的参数

c++ - 为什么 clang 处理这个简单的 std::variant 代码的异常?

c - C 中参数改变值

excel - 函数参数 VBA

Java apache cli 参数顺序