mercredi 27 décembre 2017

Template picks const reference over const pointer

Consider the following:

template <class T> void Foo(const T* x) {
  std::cout << "I am the pointer overload" << std::endl;
}

template <class T> void Foo(const T& x) {
  std::cout << "I am the reference overload" << std::endl;
}

Given the above, I would expect the following to call the pointer overload:

int* x;
Foo(x);

but it doesn't. That seems odd to me as a const T* can clearly bind to a non-const T just as well as a const T& can but the pointer variant seems like a "better fit".

For my application I want the pointer variant to be called. I can make that work via an additional specialization:

template <class T> void Foo(T* x) {
  const T* const_x = x;
  Foo(const_x);
}

but that feels wrong and unnecessary. Is there a better way? What am I not understanding (other than section x.y.z of the standard says it's this way)?

Aucun commentaire:

Enregistrer un commentaire