繁体   English   中英

C ++中的模板参数

[英]Template arguments in C++

我正在阅读模板基础知识以及如何使用模板将参数传递给函数。 下面的程序我试过,运行正常,没有任何编译错误。 该函数正在修改传递给它的值,但rxcx是常量,不能修改它们。 因此,编译器应该抛出编译错误。

输出来了:

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;
}

当函数参数定义为按值传递时,如函数模板f param

template<typename T>
void f(T param) // <-- note T, and not T&

发生类型衰减 ,结果丢弃const限定符。 这种“取消资格”是有道理的,因为它实际上是传递给函数而不是 原始对象副本 (例如:原始对象可能是const ,但其副本不必)。


该函数正在修改传递给它的值,但rxcx是常量,不能修改它们。

由于上面提到的类型衰减,在你的三种情况下, T被推断为int (即:不合格)。 该函数实际上是修改非const正在传递的对象的副本。 因此,您没有看到任何编译错误。

f每次使用都是修改传递给它的值的副本 这些副本都不是const & ,因此修改它们非常好

使用模板参数中的T ,删除constvolatile& 同样的规则适用于auto 这称为类型衰减。

所以在每种情况下只使用一个函数void f (int param)

 f(x); // argument is int, T is int, param's type is int
 f(cx); // argument is const int, T is int, param's type is int 
 f(rx); // argument is const int &, T is int, param's type int

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM