Value initialization of temporary void object in return statement [duplicate]
Asked Answered
L

1

6

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?

Literator answered 20/6, 2023 at 19:10 Comment(4)
I think the bit about T() and T{} behaving the same when initializing an object is a red herring. void is an incomplete type, there is no such thing as a void object, so whatever void() is doing it's not initializing one. Suspect the answer has to do with what exactly is governing the validity of return void()Mandarin
related #57982109Lucier
Looks like a clang bug/missing feature. Until C++20, only T() was allowed when T was void. C++20 allowed using {} and it has the same behavior so clang should accept it.Nevertheless
void object? wut?Earthshaker
H
5

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

void() and void{} are equivalent.

Hjerpe answered 20/6, 2023 at 20:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.