c++ - 为什么 C++ 不允许将 void 参数传递给具有零参数的函数?

标签 c++ templates overloading language-lawyer void

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/

相关文章:

c++ - 使用模板类 C++ 重新创建 vector

c++ - 从函数返回结构和内存分配

templates - 用于 Web 开发的 QuickStart 基本布局/模板?

c++ - 3D 应用中的 OpenGL 2D hud

c++ - CUDA 主动扭曲与常驻扭曲

c++ - 是否有可能为模板函数的所有模板参数使用一个版本的机器代码?

具有相同名称但返回类型不同的 C++ 模板函数

c++ - 使用 SystemTap 重载 c++ 方法分析

c++ - 如何根据对象是否为右值引用路由到不同的实现?

java - java 难道不应该将重载函数与大多数特定类型相匹配吗?