2

C++ introduced class template argument deduction so instead of

std::array<int, 33> arr{1,2,3,...};
std::vector<float> vec{0.0, 0.1, 0.01, ...};
std::pair<int, float> pair {1, 1.1};

we can write cleaner code

std::array arr{1,2,3,...};
std::vector vec{0.0, 0.1, 0.01, ...};
std::pair pair {1, 1.1};

But, when we make a type alias with the same template parameters deduction fails for some reason

#include <array>
template<class T, size_t N>
array_alias = std::array<T, N>;

int main() {
  array_alias array {1,2,3}; // expected array_alias<int, 3>
  return 0
}

I've expected it will use same deduction method, but for some reason every compiler throws an error. What's the difference with alias template and class template and is there a way to make it work?

Sugar
  • 490
  • 9
  • 22
  • 2
    See [Deduction_for_alias_templates (C++20)](https://en.cppreference.com/w/cpp/language/class_template_argument_deduction#Deduction_for_alias_templates). – Jarod42 Oct 27 '21 at 10:14
  • 2
    Related https://stackoverflow.com/questions/69342182/how-can-i-give-two-compatible-names-to-a-c-class-template-with-deduction-guide/69342585#69342585 – 康桓瑋 Oct 27 '21 at 10:25
  • @Jarod42 so basically it's should be fixed in c++20? – Sugar Oct 27 '21 at 10:28
  • @Sugar: Yes, it should be. – Jarod42 Oct 27 '21 at 10:31
  • @Sugar: It’s not a “fix”—CTAD for alias templates (which need not be as trivial as this one) is a sophisticated, complicated feature that was added when it was ready. – Davis Herring Oct 27 '21 at 13:30
  • @RaymondChen yes. you can close mine question as dupe. – Sugar Oct 28 '21 at 10:38
  • @DavisHerring c++14 also did compicated things, but mostly it was behavior fixes of what c++11 introduced, CTAD was introduced in c++17 and alias templates deduction proposal basically is a fix of template deduction behavior. – Sugar Oct 28 '21 at 10:44
  • @Sugar: I would definitely not call it a “fix”—it has significant additional expressive power despite being restricted to a certain form of alias template and comes with what may be the longest example in the entire standard (a full page). – Davis Herring Oct 28 '21 at 16:09

0 Answers0