无法将模板子类强制转换为其他模板实例化
Can't cast Template subclass to a different Template instantiation
假设有一个模板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> {
...
};
相关文章:
- 从C++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 约束和显式模板实例化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 将显式实例化的函数模板与转换匹配
- 无法将模板子类强制转换为其他模板实例化
- 类模板实例化中的类型转换
- 引用的静态强制转换强制模板实例化,其中不完整的类型很好
- 使用父类实例化的向下转换对象
- 模板类实例化中的指针转换无效
- Visual Studio无法在布尔运算的上下文中实例化强制转换运算符模板(T=bool)
- 为什么不能将继承自(非模板)类 B 的实例化类模板 A 的引用转换为对 B 的引用?
- 类到另一个类的实例化:Java到C++的转换
- 在没有数据重复的情况下强制转换/实例化/转换为子类/超类
- 是否将指向模板的指针强制转换为实例化该模板
- 模板化操作符实例化和类型转换
- 通过强制转换OpenCV UMat的句柄实例化OpenCL cl_mem
- 转换基指针时出错:“不能实例化抽象类”