C++ operator lookup misunderstanding

时光总嘲笑我的痴心妄想 提交于 2019-12-10 19:04:47

问题


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";
}

回答1:


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";
}



回答2:


Can you check which type is used in template, is it int or int*? I suspect that you inspecting T to be int, but compiler interpret T as a int* and use reference template.

Try to use

test<int>(p);

to specify type explicity



来源:https://stackoverflow.com/questions/34357559/c-operator-lookup-misunderstanding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!