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?

Fedor
  • 17,146
  • 13
  • 40
  • 131
  • 3
    I think the bit about `T()` and `T{}` behaving the same when initializing an object is a red herring. `void` is an [incomplete type](https://en.cppreference.com/w/cpp/language/types#Void_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()` – Nathan Pierson Jun 20 '23 at 19:24
  • related https://stackoverflow.com/questions/57981609/return-statement-that-calls-a-function-that-returns-void-in-a-function-that-retu – 463035818_is_not_an_ai Jun 20 '23 at 19:26
  • 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. – NathanOliver Jun 20 '23 at 19:29
  • `void` object? wut? – Language Lawyer Jun 21 '23 at 08:28

1 Answers1

5

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

void() and void{} are equivalent.

duck
  • 1,455
  • 2
  • 8