将模板类转换为标头和 cpp 文件

Converting a template class to a header and cpp file

本文关键字:cpp 文件 转换      更新时间:2023-10-16

我试图将以下头文件转换为单独的头文件和.cpp文件。

template <class T>
class Rolodex {
public:
/**
* Creates a new empty Rolodex
*/
Rolodex()
{
sentinel_ = new Item;
sentinel_->value_ = T();
sentinel_->next_  = sentinel_;
sentinel_->prev_  = sentinel_;
current_ = sentinel_;
}
~Rolodex()
{
while (current_ != sentinel_) {
delete_current();
}
delete sentinel_;
}
/**
* Returns true if the Rolodex is positioned at the beginning.
*/
bool is_before_first()
{
return current_ == sentinel_;
}
/**
* Returns true if the Rolodex is positioned at the end.
*/
bool is_after_last()
{
return current_ == sentinel_;
}
/**
* Rotates the Rolodex one step forwards.
*/
void rotate_forward()
{
current_ = current_->next_;
}
/**
* Rotates the Rolodex one step backwards.
*/
void rotate_backward()
{
current_ = current_->prev_;
}
/**
* Returns the value of the current card.
*/
const T &current_value()
{
return current_->value_;
}
/**
* Inserts a new item after the current position and
* positions the Rolodex at the newly inserted item.
*/
void insert_after_current(const T &value)
{
Item *coming = new Item;
coming->value_ = value;
coming->next_  = current_->next_;
coming->prev_  = current_;
current_->next_->prev_ = coming;
current_->next_ = coming;
current_ = coming;
}
/**
* Inserts a new item before the current position and
* positions the Rolodex at the newly inserted item.
*/
void insert_before_current(const T &value)
{
Item *coming = new Item;
coming->value_ = value;
coming->prev_  = current_->prev_;
coming->next_  = current_;
current_->prev_->next_ = coming;
current_->prev_ = coming;
current_ = coming;
}
/**
* Deletes current item and positions the Rolodex
* at the _following_ item
*/
void delete_current()
{
Item *going = current_;
current_->prev_->next_ = current_->next_;
current_->next_->prev_ = current_->prev_;
if (going->next_ == sentinel_)
current_ = going->prev_;
else
current_ = going->next_;
delete going;
}
private:
struct Item {
T value_;
Item *next_;
Item *prev_;
};
Item *sentinel_;
Item *current_;
};
#endif /* ROLODEX_H_ */

但是,当我将它们分开时,如果我不包括

template <class T>

在头文件中,我收到一个错误,试图声明

T value;

但是如果我这样做,我会在.cpp文件中收到多个错误,说 Rolodex 不是文件类或枚举。是否有其他类型可用于声明我的值;如果是这样,我该如何修改代码以适应这一点。任何帮助都非常感谢,我超级迷路

编辑:谢谢大家的帮助,我对C++类缺乏理解,在对您提供的类似线程进行一些研究后,我解决了我的问题。

如果您不知道模板的工作原理,我建议您先阅读该主题。

您可以在单独的.cpp文件中定义模板类成员,但还必须为要使用的所有类型实例化一个类。您可以在.h.cpp文件中声明一个简单的虚拟对象。

// tmpl.h
template <typename T>
struct S {
S();
T _a_field;
}
// tmpl.cpp
template <typename T>
S<T>::S() {}
S<int> dummy;

但是,这不是建议的方法。我个人建议在单个tmpl.h文件或另一个文件中定义所有内容,并将其包含在tmpl.h

使用模板时,完整的实现需要在标头中。不能将.cpp文件用于方法定义,但如果您仍希望分离接口和实现。可以将.hpp用于类定义,.inl文件用于方法定义。在.hpp文件的末尾,您必须包含包含该实现的.inl文件。您可以在此处了解更多信息,为什么模板代码无法移动到.cpp文件 https://youtu.be/6wdCqNlnMjo