omicronns
omicronns

Reputation: 357

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;
}

Upvotes: 4

Views: 239

Answers (2)

user7860670
user7860670

Reputation: 37587

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

Upvotes: 2

T.C.
T.C.

Reputation: 137394

The specialization called, const int foo2<const int>(const int&);, has a return type of const int, so foo2(x) would have been a prvalue of type const int. However, There are no const (or volatile) prvalues of non-array, non-class type (in your case, int). The constness is adjusted away "prior to any further analysis", and it becomes simply a prvalue of type int, which decltype reports.

Upvotes: 6

Related Questions