R
R
rus_prog2021-12-08 18:18:29
OOP
rus_prog, 2021-12-08 18:18:29

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;
}

Is it possible to fix this somehow? Or do you need to specialize for all types?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
C
cunion, 2021-12-09
@rus_prog

template<class U, int Size>remove it and it will work

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question