Why does my overloaded template function advertise a constant differently than a function without a template.

I have an overloaded function that works correctly. (f in the example). When I convert it to a template version of the same, it is interrupted, always calling T & versions, never T *. (t in the example) When I create a non-constant version of the template function, it works as expected. (t2 in the example) This happens both in VS2010 and in g ++ 4.6.2. Are the rewards for constant rules different, or is this some kind of mistake.

#include <iostream> using namespace std; int f(const int&x){return 1;} int f(const int*x){return 2;} template <class T> int t(const T &x){return 3;} template <class T> int t(const T *x){return 4;} template <class T> int t2(T &x){return 5;} template <class T> int t2(T *x){return 6;} int main(int argc, char ** argv){ int x=0; cout<<f(x)<<endl; cout<<f(&x)<<endl; cout<<t(x)<<endl; cout<<t(&x)<<endl; cout<<t2(x)<<endl; cout<<t2(&x)<<endl; return 0; } 

output

 1 2 3 3 5 6 
+4
source share
2 answers

Your int x not const . So &x gives a int* . Here are two candidate functions:

  • int t<int*>(T const&) (equivalent to int t<int*>(int * const&) ) <-T is int* ; 0 conversions required
  • int t<int>(T const*) (equivalent to int t<int>(int const*) ) <-T is int ; requires conversion from int* to int const*

The best match is selected, i.e. one without conversion. This is a reference version.

+5
source

In these two cases:

 cout<<t(x)<<endl; cout<<t(&x)<<endl; 

overloading template <class T> int t(const T &x) is selected by the compiler, because T can be satisfied by int and int * respectively.

In this case:

 cout<<t2(&x)<<endl; 

overload template <class T> int t2(T &x) not selected because it cannot be executed. You cannot bind a link to a temporary (rvalue), and &x is temporary.

+2
source

Source: https://habr.com/ru/post/1388832/


All Articles