Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic template deduction C++20 with aggregate type

I am puzzled about this C++ code:

template <class T>
struct Foo {
  T value;
};
 
int main() {
    return Foo<int>(0).value;
    // Below code works as well in gcc
    // return Foo(0).value;
}

It compiles with GCC 10 in C++20 standard (but not in C++17 standard) and latest MSVC, but not with clang 13 or 14, even in C++20.

According to the standard (from cppreference) it should be possible to instantiate Foo at least when specifying the templated type.

Why is this related to C++20 ? I see nothing that change in the template deduction specification (I maybe missed something).

Also (this is strange), GCC in C++20 mode even compiles when we call Foo without specifying templated type (Foo(0)).

godbolt link here

like image 241
Stéphane Janel Avatar asked Dec 07 '21 13:12

Stéphane Janel


People also ask

What is template deduction?

Template argument deduction is used when selecting user-defined conversion function template arguments. A is the type that is required as the result of the conversion. P is the return type of the conversion function template.

What is type deduction c++?

Type inference or deduction refers to the automatic detection of the data type of an expression in a programming language. It is a feature present in some strongly statically typed languages. In C++, the auto keyword(added in C++ 11) is used for automatic type deduction.

Can constructors be templated?

As long as you are satisfied with automatic type inference, you can use a template constructor (of a non-template class). @updogliu: Absolutely.

How do you call a function template in C++?

Defining a Function TemplateA function template starts with the keyword template followed by template parameter(s) inside <> which is followed by the function definition. In the above code, T is a template argument that accepts different data types ( int , float , etc.), and typename is a keyword.


Video Answer


1 Answers

It compiles with GCC 10 in C++20 standard (but not in C++17 standard) and latest MSVC.

This is because GCC 10 and the latest MSVC implement allow initializing aggregates from a parenthesized list of values, which allows us to use parentheses to initialize aggregates.

Also (this is strange), GCC in C++20 mode even compiles when we call Foo without specifying templated type (Foo(0)).

This is because GCC 10 implements class template argument deduction for aggregates, which makes T automatically deduced to int.


Please note that clang does not currently implement these two C++20 features, so your code cannot be accepted by clang.

You can refer to cppreference to get the current compiler's support for C++20 features.

like image 191
康桓瑋 Avatar answered Oct 27 '22 23:10

康桓瑋