C++运算符查找错误
C++ operator lookup misunderstanding
我遇到了下一个问题:
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 *
意味着T
是const
而不是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);
指定类型显式
相关文章:
- 查找显示链表时出现的错误
- enable_if继承的成员函数的名称查找错误
- 用于查找数组中最大元素的出现次数的代码,给出分段错误
- 使用 c++ 查找 lapindromes 时运行时错误"SIGCONT"
- 旧C++代码中的目录查找导致 OS X Catalina 10.15 中的目录错误
- 尝试查找两组点的交集,错误"No viable overloaded '=' "
- 在尝试使用递归查找集合子集的总数时,我遇到了分割错误
- 查找素数:错误:控件到达非void函数的末尾
- DEV C++ 第 69 行 [错误] ISO "for" 范围更改了"i"的名称查找 [-允许]
- 与Qt交叉编译到Raspberry Pi 3B+通讯录(协议缓冲区)-错误符号查找错误
- 如何修复错误:使用向量查找最小值和最大值进行合并排序
- 需要一些帮助来查找我的程序中的逻辑错误
- OpenCV CV 查找单应断言错误计数器 = > 4
- 我的代码似乎在查找最大数字时存在语法错误
- 在编写代码以查找数组中的对数时获取分段错误
- 符号查找错误未定义的符号:curl_mime_init
- 从模板实例化/类型推断中查找错误消息的实际来源
- 质数查找器运行时错误
- 我在代码中收到一个运行时错误,该错误如何通过修改最多一个元素来查找数组是否可以变得不减少
- 分段错误 - 查找列表的根