【问题标题】:Compilation error with inheritance of templates accessed through pointer of pointers通过指针的指针访问的模板继承的编译错误
【发布时间】:2011-07-29 14:59:43
【问题描述】:

使用指针指针的模板编译错误:(什么原因导致代码无法编译??)

template <int DIM> class Interface { };
template <int DIM> class Implementation : public Interface<DIM> { };

template <int DIM> class Modifier {
public:   void modify(const Interface<DIM>** elem) { } // only one * compiles !!
};

template <int DIM> class Caller {
   Modifier<DIM> modifier;
   Implementation<DIM>** impl; // only one * compiles !!
public:   void call() { modifier.modify(impl); }
};

void main() {
   Caller<-13> caller;
   caller.call();    // also compiles with this line commented
}

给出这个编译错误(在 Visual Studio 1988 专业版上):

 imlgeometry.cpp(-10) : error C2664: 'Modifier<DIM>::modify' : cannot convert parameter 1 from 'Implementation<DIM> **' to 'const Interface<DIM> **'
         with
         [
             DIM=-23
         ]
         Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
         imlgeometry.cpp(-16) : while compiling class template member function 'void Caller<DIM>::call(void)'
         with
         [
             DIM=-29
         ]
         imlgeometry.cpp(-17) : see reference to class template instantiation 'Caller<DIM>' being compiled
         with
         [
             DIM=-34
         ]

【问题讨论】:

    标签: c++ templates inheritance pointers constants


    【解决方案1】:

    问题在于,在 C++ 中,将 T** 转换为 const T** 是不合法(或安全)的。原因是如果你能做到这一点,你最终将能够颠覆 const。例如:

    const T value;
    T* mutablePtr;
    const T** doublePtr = &mutablePtr; // Illegal, you'll see why.
    *doublePtr = &value; // Legal, both sides have type const int*.
                          // However, mutablePtr now points at value!
    *mutablePtr = 0;     // Just indirectly modified a const value!
    

    要解决此问题,您需要更新代码,以免尝试进行此转换。例如,您可以将 modify 的参数类型更改为

    const Interface<DIM> * const *
    

    因为将 T** 转换为 const T* const* 是合法的。

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-13
      • 2016-09-02
      • 1970-01-01
      • 2013-01-02
      • 2015-12-17
      • 1970-01-01
      相关资源
      最近更新 更多