2 years ago

#11976

test-img

Fedor

Declare several variables with template type auto-deduction from default parameter

In the following program struct B is parametrized by a non-type template argument with default value of a lambda object:

template <auto = []{}>
struct B {};

// ok everywhere
[[maybe_unused]] B<> b1, b2;
static_assert( std::is_same_v<decltype(b1), decltype(b2)> );

// ok in GCC only
[[maybe_unused]] B b3, b4;
static_assert( !std::is_same_v<decltype(b3), decltype(b4)> );

If two variables are declared as B<> b1, b2 then they both have the same type. But if one declares B b3, b4 then GCC makes them of distinct types (each with its own lambda). At the same time MSVC and Clang refuse to accept it. MSVC error:

<source>(11): error C3538: in a declarator-list 'B' must always deduce to the same type
<source>(11): note: could be 'B<<lambda_2_>{}>'
<source>(11): note: or       'B<<lambda_3_>{}>'

Clang error is more confusing:

error: template arguments deduced as 'B<{}>' in declaration of 'b3' and deduced as 'B<{}>' in declaration of 'b4'

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

Which compiler is right here?

c++

templates

lambda

language-lawyer

template-argument-deduction

0 Answers

Your Answer

Accepted video resources