我正在尝试使用隐含指针来创建一个解决方法,以掩盖库的大部分内部结构,同时仍保留基本功能。目前我依赖于模板,下面的代码会产生以下我不知道如何解决的编译器错误:
prog.cpp: In function ‘int main()’:
prog.cpp:55:10: error: no match for ‘operator=’ (operand types are ‘std::auto_ptr<TypeAdapter_impl<mytype> >’ and ‘TypeAdapter_impl<mytype>*’) t._impl = tam;
代码如下:
#include <iostream>
#include <memory>
using namespace std;
typedef long document_ptr;
class mytype {
public:
mytype(document_ptr d) {
a = d;
std::cout << "Instantiated mytype with document_ptr " << a << "\n";
}
document_ptr a;
};
class TypeContainer {
public:
void * _t;
TypeContainer(void * t) { _t = t; }
~TypeContainer() { delete _t; }
// TODO operator *
};
class DocumentContainer {
public:
document_ptr * doc;
};
template<class Type>
class TypeAdapter_impl
{
public:
TypeAdapter_impl() { }
~TypeAdapter_impl() { }
TypeContainer TypeFactory(DocumentContainer& d){
Type * t = new Type(d.doc);
return TypeContainer(t);
}
};
template<class Type>
class TypeAdapter
{
public:
std::auto_ptr< TypeAdapter_impl<Type> > _impl;
};
int main() {
// your code goes here
TypeAdapter<mytype> t;
TypeAdapter_impl<mytype> * tam = new TypeAdapter_impl<mytype>;
t._impl = tam;
DocumentContainer d;
d.doc = new document_ptr(10);
mytype m = t._impl->TypeFactory(d);
return 0;
}
如有任何帮助,我们将不胜感激!
最佳答案
您在问题中提到的错误是由以下原因引起的:
std::auto_ptr
中没有operator=
,其中 RHS 的类型为T*
。- 构造函数
std::auto_ptr::auto_ptr(T*)
是显式的(See reference)。
这行不通。
std::auto_ptr<int> a;
int* b = new int;
a = b;
这有效。
std::auto_ptr<int> a;
int* b = new int;
a = std::auto_ptr<int>(b);
根据您的情况,更改线路
t._impl = tam;
到
t._impl = std::auto_ptr<TypeAdapter_impl<mytype>>(tam);
消除编译器错误。
您的代码中还有其他问题。
~TypeContainer() { delete _t; }
不会工作,因为 _t
的类型是 void*
。
mytype m = t._impl->TypeFactory(d);
不会工作,因为 TypeAdapter_impl::TypeFactory()
的返回类型是 TypeContainer
并且无法转换 TypeContainer
到 mytype
。
线
Type * t = new Type(d.doc); // FIXME document_ptr not defined here!
也不对。 doc
,如 main
中所定义,指向一个包含 10 个元素的数组。不确定您对使用哪一个感兴趣。将其更改为:
Type * t = new Type(d.doc[0]);
消除编译器错误。
关于c++ - 编译器错误 : Template class assignment no match,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26835327/