void f()
{}
void f(int)
{
return f(); // #1: ok
}
void g(auto fn)
{
f(fn());
}
int g1()
{
return 0;
}
void g2()
{}
int main()
{
g(g1); // #2: ok
g(g2); // #3: error
}
C++ 允许显式返回空值,如
#1
所示,我认为它优雅而通用。但是,该规则不能应用于
#3
以同样的方式。为什么 C++ 不允许将 void 参数传递给具有零参数的函数?
最佳答案
因为语言指定调用中的每个参数表达式初始化函数的一个参数
[expr.call/7]
When a function is called, each parameter is initialized with its corresponding argument.
在没有参数的函数中,没有要初始化的第一个参数,即使有,
void
是没有值的类型。
关于c++ - 为什么 C++ 不允许将 void 参数传递给具有零参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61539389/