简体   繁体   中英

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. 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 :

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. 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).


The function is modifying the value passed to it but rx and cx are constants and they cannot be modified.

Because of the type decay mentioned above, in your three cases T is deduced to be int (ie: unqualified). The function is actually modifying a non- const copy of the object being passed. Therefore, you don't see any compilation error.

Each usage of f is modifying a copy of the value passed to it. None of those copies are const & , so modifying them is perfectly fine

With T from the the template parameter, const , volatile and & are removed. Same rule applies to auto . This is called type decaying.

So in every case only one function is used 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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