Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
}
like image 840
Kurz Avatar asked Nov 25 '25 14:11

Kurz


1 Answers

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";
}
like image 70
linux40 Avatar answered Nov 27 '25 06:11

linux40



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!