2011-07-29 101 views
1

模板编译错误的指针访问模板继承编译错误:(是什么原因导致这些代码并没有编译??)与通过使用指针的指针的指针

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 
     ] 
+0

VS1988?这是_old _... –

回答

1

问题是,在C++中,将T **转换为常量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! 

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

const Interface<DIM> * const * 

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

希望这会有所帮助!