模板中的const_cast。是否有不整数修饰符? [英] const_cast in template. Is there a unconst modifier?

查看:134
本文介绍了模板中的const_cast。是否有不整数修饰符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的模板类:

 模板< T& 
class MyClass
{
T * data;有时,我想使用具有常量类型T的类如下:
}



<

  MyClass< const MyObject> mci; 

但我想使用 const_cast< MyObject *> data (这不重要为什么,但 MyClass 是一个引用计数智能指针类,它保持数据本身的引用计数 MyObject 是从包含计数的某种类型派生的
数据不应被修改,但计数必须由智能指针修改。)



有没有办法从 T 删除常量?虚构代码:

  const_cast< unconst T>(data)

解决方案

这里最简单的方法是但是,如果你对如何使用 const_cast 感兴趣,那么重新实现boost的

code> 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


I have a template class like this:

template<T>
class MyClass
{
  T* data;
}

Sometimes, I want to use the class with a constant type T as follows:

MyClass<const MyObject> mci;

but I want to modify the data using const_cast<MyObject*>data (it is not important why but MyClass is a reference count smart pointer class which keeps the reference count in the data itself. MyObject is derived from some type which contains the count. The data should not be modified but the count must be modified by the smart pointer.).

Is there a way to remove const-ness from T? Fictional code:

const_cast<unconst T>(data)

?

解决方案

The simplest way here would be to make the reference count mutable.

However, if you are interested in how it would work with the const_cast, then reimplementing boost's remove_const should be quite simple:

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();

这篇关于模板中的const_cast。是否有不整数修饰符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆