Search code examples
c++pointersreferenceoverloadingoperator-precedence

C++ operator lookup misunderstanding


I have a trouble with next 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 test() method will always pass to overloading with reference. Even this:

int *p = 0; test(p);

Can someone tell me why reference has so high priority and the place in standart where to read about this.

Oh... I was inattentive! I have to specify both const and non-const overloading for a 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";
}

Solution

  • Because const T * means that T is 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;
    }
    

    You can also use typedef T * PtrT, and then change T * const to const PtrT.

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