c++ - 编译器错误 : Template class assignment no match

标签 c++ templates

我正在尝试使用隐含指针来创建一个解决方法,以掩盖库的大部分内部结构,同时仍保留基本功能。目前我依赖于模板,下面的代码会产生以下我不知道如何解决的编译器错误:

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;
}

如有任何帮助,我们将不胜感激!

最佳答案

您在问题中提到的错误是由以下原因引起的:

  1. std::auto_ptr 中没有 operator=,其中 RHS 的类型为 T*
  2. 构造函数 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 并且无法转换 TypeContainermytype

线

    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/

相关文章:

templates - 需要模板的任何实例

header 或源代码中的 C++ 函数修饰符?快速引用

c++ - 在序列中找到最小奇数和最大偶数

c++ - 关于如何将旧式嵌入式应用程序限制为实时应用程序的建议

c++ - 函数模板返回类型推导

c++ - 为什么递归可变参数模板不能按预期工作?

c++ - 模板参数修饰符

c++ - 是否需要释放本地时间的内存?

c++ - Asio 对 OpenSSL 的依赖

c++ - clang 无法在模板实例化时生成默认的移动构造函数