C++继承具有模板成员函数的类
C++ Inherit class with template member function
我在编写资源类时遇到问题
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&__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;
}
};
相关文章:
- 对RValue对象调用的LValue ref限定成员函数
- 为什么使用 "this" 指针调用派生成员函数?
- 将公共但非静态的成员函数与ALGLIB集成
- 使用指向成员的指针将成员函数作为参数传递
- 将重载的成员函数传递给函数模板
- 我不小心调用了一个没有自己类对象的成员函数.但这是怎么回事呢
- 如何在C++中使用非静态成员函数作为回调函数
- C++错误C2600:无法定义编译器生成的特殊成员函数(必须首先在类中声明)
- 关联容器的下界复杂性:成员函数与非成员函数
- 在 C++ 中用派生类型重写成员函数
- 链表的泛型函数remove()与成员函数remove)
- 如何将lambda作为模板类的成员函数参数
- constexpr构造函数需要常量成员函数时出现问题
- 将自由函数绑定为类成员函数
- 区分非成员函数和头文件中的成员函数
- 如何从子成员函数修改父公共成员变量
- 保留对其他类的成员函数的引用
- 在运算符重载定义中使用成员函数(const错误)
- 内联如何影响模块接口中的成员函数
- 将成员函数指针作为参数传递给模板方法