Mar 9, 2022

[C++17] non-type with 'auto's specialized variable template can have different type

Reference:
https://en.cppreference.com/w/cpp/language/template_parameters#Non-type_template_parameter

http://eel.is/c++draft/range.elements#overview-2


First of all, the behavior of non-type (auto) variable template is same as template class with non-type (auto) parameter. Both its specialized non-type (auto) type is detached from its primary declared template.

e.g.

template <auto X> auto foo = X;

template <> unsigned int foo<42> = 42;

int main() {
  auto f1 = foo<true>; // auto is 'bool' type
  auto f2 = foo<42>;   // auto is 'unsigned int' type
}


template <auto N> struct Fun { static constexpr auto n = N; };

template <> struct Fun<42> { static constexpr auto n = 422; };

int main() {

  auto f1 =  Fun<true>::n; // auto is 'bool' type
  auto f2 = Fun<42>::n; // auto is 'int' type
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.