删除模板函数中的常量
removing constness in 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;
}
当我 运行 我得到:
error C2440: 'const_cast' : cannot convert from 'int' to 'int'
如何在我的函数中使用 const_cast
。
你可以尝试这样做:
template< typename T>
void fct(const T& param)
{
const_cast<T&>(param) = 40;
}
模板类型 T 必须是引用,否则您的转换没有任何意义
const_cast<T>(param) = 40;
不是你想要的,因为 fct(cx);
和 fct(rx);
,T
被推断为 const int
。
如果你想去除常量,即获取对非常量的引用,你可以使用std::remove_const
:
const_cast<typename std::remove_const<T>::type &>(param) = 40;
由于T
推导为const int
,typename std::remove_const<T>::type
推导为int
,则上述代码与const_cast<int &>(param)...
相同。
注意 cx
是一个常量,试图通过从 const_cast
获得的引用修改它会导致 UB。 rx
没关系,其实指的是非常数
我在删除使用模板函数的常量性时遇到了一点问题。
#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;
}
当我 运行 我得到:
error C2440: 'const_cast' : cannot convert from 'int' to 'int'
如何在我的函数中使用 const_cast
。
你可以尝试这样做:
template< typename T>
void fct(const T& param)
{
const_cast<T&>(param) = 40;
}
模板类型 T 必须是引用,否则您的转换没有任何意义
const_cast<T>(param) = 40;
不是你想要的,因为 fct(cx);
和 fct(rx);
,T
被推断为 const int
。
如果你想去除常量,即获取对非常量的引用,你可以使用std::remove_const
:
const_cast<typename std::remove_const<T>::type &>(param) = 40;
由于T
推导为const int
,typename std::remove_const<T>::type
推导为int
,则上述代码与const_cast<int &>(param)...
相同。
注意 cx
是一个常量,试图通过从 const_cast
获得的引用修改它会导致 UB。 rx
没关系,其实指的是非常数