dan*_*tel 5 c++ templates const const-cast
我有这样的模板类:
template<T>
class MyClass
{
T* data;
}
Run Code Online (Sandbox Code Playgroud)
有时,我想使用具有常量类型T的类,如下所示:
MyClass<const MyObject> mci;
Run Code Online (Sandbox Code Playgroud)
但我想使用修改数据const_cast<MyObject*>data(这不是重要的原因,但它MyClass是一个引用计数智能指针类,它将引用计数保留在数据本身.MyObject是从包含计数的某种类型派生的.数据不应该被修改但是必须通过智能指针修改计数.
有没有办法从中删除常量T?虚构代码:
const_cast<unconst T>(data)
Run Code Online (Sandbox Code Playgroud)
?
Unc*_*ens 12
这里最简单的方法是使引用计数可变.
但是,如果你对如何使用它感兴趣const_cast,那么重新实现boost remove_const应该非常简单:
template <class T>
struct RemoveConst
{
typedef T type;
};
template <class T>
struct RemoveConst<const T>
{
typedef T type;
};
const_cast<typename RemoveConst<T>::type*>(t)->inc();
Run Code Online (Sandbox Code Playgroud)
你有答案.const_cast在两个方向上工作:
char* a;
const char* b;
a = const_cast<char*>(b);
b = const_cast<const char*>(a); // not strictly necessarily, just here for illustration
Run Code Online (Sandbox Code Playgroud)
至于你的具体问题,你考虑过mutable关键字吗?它允许在const方法中修改成员变量.
class foo {
mutable int x;
public:
inc_when_const() const { ++x; }
dec_when_const() const { --x; }
};
Run Code Online (Sandbox Code Playgroud)