C ++ Operator Search Failure

I am having problems with the following case:

template<typename T>
void test(const T &ref){
     cout << "By reference";
}

template<typename T>
void test(const T *ptr){
     cout << "By pointer";
}

Any parameter that I sent to the method test()will always go to overload using the link. Even this:

int *p = 0; test(p);

Can someone tell me why the link has such a high priority and a place in the standard where you can read about it.

Oh ... I was inattentive! I have to specify both const and non-const overload for the pointer case:

template<typename T>
void test(const T &ref){
     cout << "By reference";
}

template<typename T>
void test(T *ptr){
     cout << "By pointer";
}

template<typename T>
void test(const T *ptr){
     cout << "By const pointer";
}
+4
source share
2 answers

Because it const T *means that it Tis const, but not T *.

#include <iostream>
template<typename T>
void test(const T &ref){
     std::cout << "By reference\n";
}

template<typename T>
void test( T * const ptr){
     std::cout << "By pointer\n";
}


int main()
{
    int *p;
    test(p);
    return 0;
}

typedef T * PtrT, T * const const PtrT.

template <typename T>
using PtrT = T *;

template<typename T>
void test(const PtrT<T> ptr){
     std::cout << "By pointer\n";
}
+3

, , int int *? , , T int, T int * .

test<int>(p);

0

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


All Articles