C++运算符查找错误

C++ operator lookup misunderstanding

本文关键字:错误 查找 运算符 C++      更新时间:2023-10-16

我遇到了下一个问题:

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

我发送给test()方法的任何参数都将始终传递给带有引用的重载。即便如此:

int *p = 0; test(p);

有人能告诉我为什么参考文献具有如此高的优先级,以及在标准艺术中读到这方面的位置吗。

哦。。。我注意力不集中!我必须为指针情况指定常量和非常量重载:

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";
}
因为const T *意味着Tconst而不是T *
#include <iostream>
template<typename T>
void test(const T &ref){
     std::cout << "By referencen";
}
template<typename T>
void test( T * const ptr){
     std::cout << "By pointern";
}

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

你能检查一下模板中使用的是哪种类型吗,是int还是int*?我怀疑您检查T是否为int,但编译器将T解释为int*并使用引用模板。

尝试使用

test<int>(p);

指定类型显式