使用pointer of pointer的模板编译错误:(代码编译不通过是什么原因??)
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++ 中,将 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* 是合法的。
希望这对您有所帮助!
关于c++ - 通过指针的指针访问的模板继承的编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6875069/