Search code examples
c++c++11templatesconstantsconst-cast

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.


Solution

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