【发布时间】:2011-04-04 11:01:39
【问题描述】:
刚接触 C++ 并从书本中学习,所以我的推理可能相当迂腐或短视。
在模板函数的情况下,我读过当一个参数通过 Reference 传递时,只允许从 Reference / Pointer to NonConst 到 Reference / Pointer to Const 的转换。
这意味着我相信
template <typename T> int compare(T&, T&);
在调用 compare(ci1, ci1) 时应该会失败,其中 ci1 是常量 int,因为 Reference 参数不允许从 Const 转换为 NonCost。
但是它在我的编译器 (Visual C++ 10) 中有效。有人可以解释一下我哪里做错了吗?
template <typename T> int compare(T&, T&);
template <typename T> int compare(T &v1, T &v2)
{
// as before
cout << "compare(T, T)" << endl;
if (v1 < v2) return -1;
if (v2 < v1) return 1;
return 0;
}
const int ci1 = 10;
const int ci2 = 20;
int i1 = 10;
int i2 = 20;
compare(ci1, ci1);
compare(i1, i1);
【问题讨论】:
标签: c++ templates function parameters reference