代码之家  ›  专栏  ›  技术社区  ›  danatel

常量转换模板。是否有无约束修饰符?

  •  5
  • danatel  · 技术社区  · 15 年前

    我有一个这样的模板类:

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

    有时,我希望使用具有常量类型t的类,如下所示:

    MyClass<const MyObject> mci;
    

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

    有没有办法消除 T ?虚构代码:

    const_cast<unconst T>(data) 
    

    ?

    5 回复  |  直到 7 年前
        1
  •  12
  •   UncleBens    15 年前

    这里最简单的方法是使引用计数可变。

    但是,如果您对它将如何与 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();
    
        2
  •  5
  •   jmucchiello    15 年前

    你知道答案了。两个方向的施工图:

    char* a;
    const char* b;
    
    a = const_cast<char*>(b);
    b = const_cast<const char*>(a); // not strictly necessarily, just here for illustration
    

    至于你的具体问题,你考虑过可变关键字吗?它允许在const方法中修改成员变量。

    class foo {
        mutable int x;
    public:
        inc_when_const() const { ++x; }
        dec_when_const() const { --x; }
    };
    
        3
  •  4
  •   Jerry Coffin    15 年前

    使引用计数在由侵入指针管理的类中可变。这是完全合理的,并且完全正确地反映了“逻辑常量”——也就是说,更改对象的引用计数并不反映对象本身状态的任何更改。换句话说,在逻辑上,引用计数不是对象的一部分——对象恰好是存储这个半无关数据的一个方便的地方。

        4
  •  3
  •   Bojan Resnik    15 年前

    如果可以使用boost,类型特征库将提供 remove_const 这样做的元函数。

        5
  •  0
  •   mpb    7 年前

    这是我的C++ 11 unconst 功能 template .

    如果你用它,你就是在调情 undefined behavior . 你一直 警告 .

    // on Ubuntu (and probably others) compile and test with                                                        
    //   g++ -std=c++11 test.c  &&  ./a.out  ;  echo $?                             
    
    template < class T >  T &  unconst  ( T const & t ) {
      return  const_cast < T & >  ( t ) ; 
    }
    
    // demonstration of use
    
    struct {
      const int n = 4;
    } s;
    
    int main () {
      unconst ( s.n ) = 5;
      return s.n;
    }
    
    推荐文章