Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing constness in templated function

I have a little issue with removing the constness of using Templated function.

#include <iostream>
using namespace std;

template< typename T>
void fct(T&  param)
{
  const_cast<T>(param) = 40;    
}


int _tmain(int argc, _TCHAR* argv[])
{
  int x = 30;
  const int  cx = x;
  const int& rx = x;
  fct(cx);
  return 0;
}

when I run this I get :

error C2440: 'const_cast' : cannot convert from 'int' to 'int'

How could I use const_cast into my function.

like image 889
Blood-HaZaRd Avatar asked Jun 04 '26 15:06

Blood-HaZaRd


1 Answers

you can try to do something like this:

template< typename T>
void fct(const T&  param)
{
  const_cast<T&>(param) = 40;    
}

template type T must be a reference or your cast does not make any sense

like image 61
Sandro Avatar answered Jun 06 '26 05:06

Sandro