5

In C++20, alias templates can have implicit deduction guides if it is applied.

Then, I have constructed a simple template alias which is ints:

template <std::size_t N>
using ints = std::array<int, N>;

but:

ints{1, 2, 3, 4}

doesn't work, and GCC said:

  • error: no matching function for call to array(int, int, int, int)
  • note: couldn't deduce template parameter N
  • note: mismatched types std::array<int, N> and int

I don't understand why it fails to compile.

And:

template <typename T>
using array_of_4 = std::array<T, 4>;

with

array_of_4{1, 2, 3, 4}

won't work either.

  • Is it because std::array's deduction guide is user-provided?
  • If the above's answer is not true, then what would be the reason?

I have found a similar question regarding this issue: How to write deduction guidelines for aliases of aggregate templates?.

This concludes that, in standard, this code should be well-formed. Hence, GCC may have different implementations that prevent this code from compiling.

Desmond Gold
  • 1,517
  • 1
  • 7
  • 19
  • 1
    The error from clang is: `error: alias template 'ints' requires template arguments; argument deduction only allowed for class templates`. – mch Nov 17 '21 at 12:24
  • clang does not support CTAD for alias templates yet (https://en.cppreference.com/w/cpp/20) – Desmond Gold Nov 17 '21 at 12:26

1 Answers1

0
ints{1, 2, 3, 4}

I don't understand why it fails to compile.

You didn't specify the template argument. This works:

ints<4>{1, 2, 3, 4}

array_of_4{1, 2, 3, 4}

won't work either.

Same problem. This works:

array_of_4<int>{1, 2, 3, 4}

std::array's deduction guide is user-provided?

Yes, it is.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • 2
    then, that would defeat the purpose of CTAD in this case? im not sure – Desmond Gold Nov 17 '21 at 12:15
  • @DesmondGold What do you mean by "defeat the purpose of CTAD"? – eerorika Nov 17 '21 at 12:16
  • 3
    I think the question is why does `std::array a {1, 2, 3, 4};` work, but `ints a {1, 2, 3, 4};` not? The compiler should be able to deduce the type to `std::array` in both cases. – mch Nov 17 '21 at 12:22