Search code examples
c++templatestemplate-argument-deduction

Template function type deduction, and return type


Why a is true, and b is false? Or in other words why T in foo1 is int const but return type of foo2 is just int?

template<typename T>
constexpr bool foo1(T &) {
    return std::is_const<T>::value;
}

template<typename T>
T foo2(T &);

int main() {
    int const x = 0;
    constexpr bool a = foo1(x);
    constexpr bool b = std::is_const<decltype(foo2(x))>::value;
}

Solution

  • const-qualifiers are ignored if function returned type is non-class, non-array type. If you use some class instead of plain int it will produce 1 1:

      struct Bar{};
    
      int main()
      {
         Bar const x{};
         constexpr bool a = foo1(x);
         constexpr bool b = std::is_const<decltype(foo2(x))>::value;
      }
    

    online compiler