下一个案子我有麻烦:
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);有人能告诉我,为什么引用有这么高的优先级和在标准的地方读到这一点。
哦..。我心不在焉!对于指针情况,我必须同时指定const和non重载:
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";
}发布于 2015-12-18 14:32:50
因为const T *意味着T是const,而不是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;
}您还可以使用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 pointer\n";
}发布于 2015-12-18 14:19:44
您能检查模板中使用哪种类型,是int还是int*?我怀疑您检查T为int,但编译器将T解释为int*并使用引用模板。
试着使用
test<int>(p);指定类型显式
https://stackoverflow.com/questions/34357559
复制相似问题