Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template argument deduction in case of designated initializers in C++

In the following code there is an initialization of A<T> objects with template argument deduction using designated initializers in two slightly distinct forms:

template<typename T>
struct A { T t; };

int main() {
   A a{.t=1};   //#1: ok in GCC and MSVC
   A b{.t={1}}; //#2: ok in MSVC only
}

The first way is accepted by both GCC and MSVC, while the second one is ok for MSVC only while GCC prints errors:

error: class template argument deduction failed:
error: no matching function for call to 'A(<brace-enclosed initializer list>)'

Demo: https://gcc.godbolt.org/z/PaEaMjM7q

Which compiler is right there?

like image 362
Fedor Avatar asked Nov 13 '21 15:11

Fedor


1 Answers

GCC is correct. Braced-init-list like {1} has no type, so it makes template argument deduction fail.

Non-deduced contexts

...

The parameter P, whose A is a braced-init-list, but P is not std::initializer_list, a reference to one (possibly cv-qualified), or (since C++17) a reference to an array:

like image 91
songyuanyao Avatar answered Oct 26 '22 19:10

songyuanyao