[英]c++ template argument deduce
template <typename T> void print(const T &) {cout("INT &");}
template <typename T> void print( T ) {cout("INT");}
int main() {
int i = 10;
print(i);
}
complier saied "error: call of overloaded 'print(int&)' is ambiguous"编译器说“错误:重载 'print(int&)' 的调用不明确”
why?为什么?
is "const T &" and "T" are the same? “const T &”和“T”是一样的吗?
template <typename T> void f( T){cout("F-T");};
template <typename T> void f( const T*){cout("F-T*");};
int main() {
int ix = 43, *p=&ix;
const int ci = 0, *p2 = &ci;
f(p); // why result is "F-T"?
}
p is the pointer,and non-const can cast const. p 是指针,非 const 可以强制转换为 const。
why f(p) choose f( T)?为什么 f(p) 选择 f(T)?
For question 1: both overloads are equally "good" with T
both deduced as int
.对于问题 1:两个重载都同样“好”, T
都推导出为int
。 It is an error to have a call where there is not a "best" overload.在没有“最佳”重载的情况下进行调用是错误的。 You get the same with你得到同样的
void print(const int &) { std::cout << "const int &"; }
void print(int) { std::cout << "int"; }
For question 2: The first overload, with T
deduced int *
, is a better than the second, with T
deduced as int
.对于问题 2:第一个重载,推导T
为int *
,比第二个重载更好,推导T
为int
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.