简体   繁体   English

使用模板类重载cout

[英]Overloading cout with template class

I'm rebuilding my class as a template and I'm having trouble with overloading cout (working without the template). 我正在重建我的课程作为模板,我在重载cout时遇到了麻烦(没有模板工作)。 gcc throws this error when I try to compile: 我尝试编译时gcc抛出此错误:

error: ‘LinkedList’ is not a type
ostream& operator <<(ostream&, LinkedList&);

The code for the LinkedList.h class is: LinkedList.h类的代码是:

template <typename value_type>

class LinkedList
{
public:
LinkedList();

~LinkedList();

void addToHead(const typename node<value_type>::value_type& entry);
void addToTail(const typename node<value_type>::value_type& entry);
void set_current(node<value_type>* entry);
void remove(string);
void remove_from_head();
void remove_from_tail();
void list_clear();

int list_length();
int count(string name);
double calcAverage();
bool search(string);
node<value_type> * get_head();
node<value_type> * get_tail();
node<value_type> * get_current();

LinkedList& operator+=(LinkedList&);

private:
node<value_type>* head;
node<value_type>* tail;
node<value_type>* current;
};
template <typename value_type>
ostream& operator <<(ostream&, LinkedList&);

I assume this has something to do with templates and that this part of the code is outside the scope of the class but different combinations of typedef and just seemed to cause more errors. 我假设这与模板有关,并且这部分代码超出了类的范围,但是typedef的不同组合似乎只会导致更多错误。

Indeed LinkedList is not a type there, it is a template . 事实上LinkedList不是那里的类型,它是一个template

You can create a type out of the template by instantiating it, substituting it's template parameters with types. 您可以通过实例化来创建模板中的类型,用类型替换模板参数。

template <typename value_type>
ostream& operator <<(ostream&, const LinkedList<value_type>&);

Edit: As suggested by @Scheff the linked listed should also be const , because the operator<< should never change it. 编辑:正如@Scheff所建议的那样,列出的链接也应该是const ,因为operator<<应该永远不会改变它。

That is because LinkedList is not a type indeed. 那是因为LinkedList确实不是一个类型。 LinkedList<int> or LinkedList<std::string> is a type. LinkedList<int>LinkedList<std::string>是一种类型。 While LinkedList<value_type> is a type template used to build actual types. LinkedList<value_type>是用于构建实际类型的类型模板。

What you need to do is to specify the template parameter as follows: 您需要做的是指定模板参数,如下所示:

template <typename value_type>
ostream& operator <<(ostream&, LinkedList<value_type>&);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM