我正在阅读模板基础知识,以及如何使用模板将参数传递给函数。我尝试了以下程序,并且运行正常,没有任何编译错误。该函数修改传递给它的值,但rx
并cx
是常数,它们不能被修改。因此,编译器应引发编译错误。
输出即将到来:
Param before : 27
Param after : 23
Param before : 27
Param after : 23
Param before : 27
Param after : 23
以下是完整的代码:
#include <iostream>
using namespace std;
template<typename T>
//void f(const T& param) // param is now a ref-to-const
void f(T param)
{
cout << "Param before : " << param << endl;
param = 23;
cout << "Param after : " << param << endl;
}
int main(int argc, char *argv[])
{
int x = 27;
const int cx = x;
const int& rx = x; // as before
// as before
// // as before
f(x); // T is int, param's type is const int&
f(cx); // T is int, param's type is const int&
f(rx); // T is int, param's type is const int&
return 0;
}
当将函数参数定义为按值传递时,如param
在函数模板中那样f
:
template<typename T>
void f(T param) // <-- note T, and not T&
甲型衰减发生,并且作为结果的const
限定符被丢弃。这种“取消资格”是有道理的,因为实际上是一个副本,什么被传递给函数,并没有将原来的对象(如:原来的对象可能是const
,但它的拷贝没有到)。
该函数修改传递给它的值,但
rx
并cx
是常数,它们不能被修改。
由于上述类型的衰变,在您的三种情况下T
被推论为int
(即:不合格)。该函数实际上是在修改const
要传递的对象的非副本。因此,您看不到任何编译错误。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句