无法将模板子类强制转换为其他模板实例化

Can't cast Template subclass to a different Template instantiation

本文关键字:转换 实例化 其他 子类      更新时间:2023-10-16

假设有一个模板stack<class T, int maxElements有一个子类Entry,它将为堆栈构建链表,所以像这样:

template <class T, int maxElements>
class Stack{
private: 
class Entry{
friend class Stack;
T info;
Entry* next;
};
Entry* first;
public:
template<class U, int n>
void append(const Stack<U, n>& s){
if(isEmpty()) first = s.first; /* here is the problem*/
....
}
};

所以,问题出在标记的行中,它是assigning to 'Stack<char, 100>::Entry *' from incompatible type 'Stack<char, 10>::Entry *const',因为它为每个模板实例化构建一个"类"条目,但关键是 Entry 不依赖于maxElement参数,所以我想知道是否有办法告诉编译器。
到目前为止,我能想到的唯一方法就是从模板中取出类,并使其本身仅基于 T 的模板

PS:我知道我在遇到错误的行中共享内存,一次一件事

问题是不同的模板实例化是不同的类型。这样,嵌套类型(在这种情况下Entry(也是不同的类型。

解决方案同样简单:将部件移动到仅取决于类型的(私有(基类:

template<typename T>
class StackBase {
protected:
struct Entry {
T info;
Entry* next;
};
};

然后从这个基类派生:

template<typename T, int maxElements>
class Stack: private StackBase<T> {
...
};