c++ - 通过指针的指针访问的模板继承的编译错误

标签 c++ templates inheritance pointers constants

使用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/

相关文章:

c++ - 为什么 C++ 允许但忽略将 const 应用于函数类型?

c# - 为什么 C# 类可以隐式和显式地从一个接口(interface)继承?

C++ 模板和继承

javascript - 下划线方法 _.template() 不编译我的模板

c++ - 如何在编译时对模板列表进行 "iterate"?

c++ - 关于 & 和 |手术

c++ - 扩展光标长度QLineEdit?

java - 检索方法或构造函数的调用者实例(不是类)

c++ - 我的代码有什么错误?

c++ - 解压缩元组列表