3

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.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
Blood-HaZaRd
  • 2,049
  • 2
  • 20
  • 43

2 Answers2

6

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

Sandro
  • 2,707
  • 2
  • 20
  • 30
  • 3
    Modifying a const object through a non-const access path is UB – AMA Jan 16 '18 at 11:22
  • Yes @AMA, but from curiousity I wanna know how to be able to remove the const ;D – Blood-HaZaRd Jan 16 '18 at 11:25
  • 2
    Aside from the fact that the indended goal is bad, I like this answer better for its simplicity. No need for type traits, let te compiler take out the `const` of the deduced type by explicitely specifying it. Of course, the different versions don't do exactly the same: this one binds to rvalues, the other one doesn't. Which can either be a pro or a con, depending on your requirements. – oisyn Jan 16 '18 at 13:49
4

const_cast<T>(param) = 40; doesn't do what you want, for both fct(cx); and fct(rx);, T is deduced as const int.

If you want to remove the constness, i.e. get a reference to non-const, you can use std::remove_const:

const_cast<typename std::remove_const<T>::type &>(param) = 40; 

For T is deduced as const int, typename std::remove_const<T>::type results in int, then the above code is same as const_cast<int &>(param)....

Note that cx is a constant, trying to modify it via reference got from const_cast leads to UB. For rx it's fine, it refers to a non-constant in fact.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405