Я пытаюсь создать обходное решение с использованием подразумеваемых указателей, чтобы затенять большинство внутренних компонентов библиотеки, сохраняя при этом базовые функции. В настоящее время я полагаюсь на шаблоны, а приведенный ниже код создает следующую ошибку компилятора, которую я не знаю, как решить:
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*)
является явным (см. Ссылку).Это не работает.
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]);
удаляет ошибку компилятора.