C++继承具有模板成员函数的类

C++ Inherit class with template member function

本文关键字:成员 函数 继承 C++      更新时间:2023-10-16

我在编写资源类时遇到问题

class BaseResource {
protected:
    unsigned int size;
public:
    virtual ~BaseResource() {}
    template<class T> const T& GetValue() const;
    template<class T, class U> void GetValue(const U& rhs);
    unsigned int GetSize() {
        return this->size;
    }
    void SetSize(unsigned int size) {
        this->size = size;
    }
};
template<class T>
class Resource : public BaseResource {
    T value;
public:
    virtual ~Resource() {}      
    Resource(unsigned int size, const T& rhs) { this->size = size; this->value = rhs; }
    const T& GetValue() const {return value;}
    void SetValue(const T& rhs) {value=rhs;}  
};

我认为上面的类定义正确,所以我不理解以下代码为什么会产生链接器错误:

Test.obj:错误LNK2001:未解析的外部符号"public:char*const&amp__thiscall BaseResource::GetValue(void)const"($GetValue@PAD@BaseResource@@QBEABQADXZ)"。

char* c = new char[3];
c[0] = '1';
c[1] = '2';
c[2] = '3';
BaseResource* resource = new Resource<char*>(3, c);
char* loadedResource = resource->GetValue<char*>();

在我看来,这应该创建一个Resource实例,该实例包含一个char*并可以返回它

有人能告诉我是我在哪里犯的错吗?

以下方法未实现:

template<class T> const T& GetValue() const;
template<class T, class U> void GetValue(const U& rhs);

我希望你不打算把它们变成虚拟的,因为这行不通。模板方法不能成为虚拟方法。由于它们没有实现,这无疑解释了链接问题。

这些函数的实现应该与类在同一个头中。在这种情况下,您已经实例化了模板函数,并且具体的实例化函数没有被挑战。任何时候使用模板时,都需要在使用该函数的翻译单元中包含该函数的定义。

编辑


这是基本理念。您需要定义植入,以便在实例化类时完全定义该类。

public:
    virtual ~BaseResource() {}
    template<class T> const T& GetValue() const
    {
       return someT;
    }
    template<class T, class U> void GetValue(const U& rhs)
    {
       return someT;
    } 
    unsigned int GetSize() {
        return this->size;
    }
    void SetSize(unsigned int size) {
        this->size = size;
    }
};