简体   繁体   English

C ++中的模板参数

[英]Template arguments in C++

I was reading template basics and how to pass arguments to functions using templates. 我正在阅读模板基础知识以及如何使用模板将参数传递给函数。 The below program I tried and is running fine without any compilation error. 下面的程序我试过,运行正常,没有任何编译错误。 The function is modifying the value passed to it but rx and cx are constants and they cannot be modified. 该函数正在修改传递给它的值,但rxcx是常量,不能修改它们。 So , there should be a compilation error thrown by the compiler. 因此,编译器应该抛出编译错误。

Output coming : 输出来了:

Param before : 27
Param after : 23
Param before : 27
Param after : 23
Param before : 27
Param after : 23

Below is the complete code: 以下是完整的代码:

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

When function parameters are defined to be passed by value , as is param in your function template f : 当函数参数定义为按值传递时,如函数模板f param

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

A type decay occurs and as a result the const qualifier is discarded. 发生类型衰减 ,结果丢弃const限定符。 This "disqualification" makes sense since is actually a copy what is being passed to the function and not the original object (eg: the original object may be const , but its copy doesn't have to). 这种“取消资格”是有道理的,因为它实际上是传递给函数而不是 原始对象副本 (例如:原始对象可能是const ,但其副本不必)。


The function is modifying the value passed to it but rx and cx are constants and they cannot be modified. 该函数正在修改传递给它的值,但rxcx是常量,不能修改它们。

Because of the type decay mentioned above, in your three cases T is deduced to be int (ie: unqualified). 由于上面提到的类型衰减,在你的三种情况下, T被推断为int (即:不合格)。 The function is actually modifying a non- const copy of the object being passed. 该函数实际上是修改非const正在传递的对象的副本。 Therefore, you don't see any compilation error. 因此,您没有看到任何编译错误。

Each usage of f is modifying a copy of the value passed to it. f每次使用都是修改传递给它的值的副本 None of those copies are const & , so modifying them is perfectly fine 这些副本都不是const & ,因此修改它们非常好

With T from the the template parameter, const , volatile and & are removed. 使用模板参数中的T ,删除constvolatile& Same rule applies to auto . 同样的规则适用于auto This is called type decaying. 这称为类型衰减。

So in every case only one function is used void f (int param) . 所以在每种情况下只使用一个函数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