2011-07-29 149 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 *是合法的。

希望這會有所幫助!