Answer the question
In order to leave comments, you need to log in
How to output class template objects with different types with overloaded output operator?
Created a class template for a singly linked list with an overloaded output operator. When I perform an output operation for classes with different types in the same block, I write an error:
error: redefinition of 'template std::ostream& operator<<(std::ostream&, const List&)'.
The code:
#include <iostream>
using namespace std;
template<class T, int size>
class List
{
public:
struct Item{
T value;
struct Item *next = nullptr;
};
struct Item* BeginList = nullptr;
int last = 0;
template<class U, int Size>
friend ostream& operator<< (ostream &os, const List<U, Size>& list){
struct Item* item = (Item*)list.BeginList;
os << "List ( " << list.last+1 << " )" << endl;
while (item){
os << item->value << endl;
item = item->next;
}
return os;
}
};
int main(){
List<int, 5> ListInt;
List<char, 5> ListChar;
cout << ListInt << endl; //тут выводит
cout << ListChar << endl; //тут ошибка
return 1;
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question