Search code examples
c++templatesoverloadinglanguage-lawyervoid

Why does C++ not allow passing a void argument to a function having zero parameters?


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++ allows explicitly returning a void value as shown at #1, I think it's elegant and generic.

However, the rule cannot be applied to #3 in the same way.

Why does C++ not allow passing a void argument to a function having zero parameters?


Solution

  • Because the language specifies that each argument expression in the call initialises a parameter of the function

    [expr.call/7]

    When a function is called, each parameter is initialized with its corresponding argument.

    In a function of no parameters, there is no first parameter to initialise, and even if there were, void is a type with no values.