0

The code compiles when the template parameter is qualified with const, like so:

template<typename T>
T increase (const T& l) {
  return l+1;
}

But it does not compile without const:

template<typename T>
T increase (T& l) {
  return l+1;
}

The compiler says:

“error: no matching function for call to ‘increase’”

My main:

int main() {
  std::cout << increase<int>(1);
}

Why does “T& l” need to be const?

  • Out of curiosity, why do you want to pass `l` as a reference (`T&`)? Why not just pass `T` in instead of `T&` ? (Also, consider using a more descriptive name, like `value` instead of short cryptic names like `l`. – Dai Aug 09 '23 at 01:47
  • 1
    Asked and answered many times: See, for instance, [Binding rvalue to const lvalue reference](https://stackoverflow.com/questions/40873500/binding-rvalue-to-const-lvalue-reference) and [Why not non-const reference to temporary objects?](https://stackoverflow.com/questions/13826897/why-not-non-const-reference-to-temporary-objects). Hope this helps. – tbxfreeware Aug 09 '23 at 02:03

0 Answers0