Search code examples
c++templatesreturnlanguage-lawyervoid

Value initialization of temporary void object in return statement


If I am not mistaken, it is allowed to write return void() in function templates to avoid unnecessary specializations and overloads for void type.

At the same time, a similar syntax return void{} is not recognized by Clang:

template<typename T>
T foo() { return T(); }

template<typename T>
T bar() { return T{}; }

int main() {
    // ok everywhere
    foo<void>();

    // error in Clang
    bar<void>();
}

Clang 16 prints the error:

error: illegal initializer type 'void'

Online demo: https://gcc.godbolt.org/z/6o89reK3G

In cppreference, I have not found the answer: both T() and T{} should behave the same for not aggregate types. And there are no special comments about void type.

Is it just a Clang bug, or on the contrary it is the only compiler strictly following the standard?


Solution

  • This is CWG2351, which is evidently not yet implemented in Clang.

    void() and void{} are equivalent.