0

I am trying to overload << operator for my exception class. My class header file looks like this:

template <typename T>
class FullContainerException
{
    public:
    Element<T>* elem;
    FullContainerException(Element<T>* elem):elem(elem){};
    template<typename U>
    friend std::ostream& operator<<(std::ostream &os, FullContainerException<T> a);
};

and my source file is this:

template<typename T>
std::ostream& operator<<(std::ostream &os, FullContainerException<T> a)
{
    return os<<"Nie udalo sie dodac elementu: "<<a.elem<<std::endl;
}

in main it is called by this:

catch (FullContainerException<int> exception)
{
    std::cout << exception << std::endl;
}

When i run it i get error that it couldn't deduce template parameter U, but in the same project i have other class which uses the same template<typename U>. Header:

template<typename T>
class Element
{
    public:
    T name;
    Element<T>* next;
    Element<T>(T name):name(name), next(NULL){};
    template<typename U>
    friend std::ostream& operator<<(std::ostream &os, Element<T>* a);
};

Source:

template<typename T>
std::ostream& operator<<(std::ostream &os, Element<T>* a)
{
    return os<<a->name;
}

Also i tried defining the overload function inside my class declaration like this:

template <typename T>
class FullContainerException
{
    public:
    Element<T>* elem;
    FullContainerException(Element<T>* elem):elem(elem){};
    friend std::ostream& operator<<(std::ostream &os, FullContainerException<T> a)
    {
        return os<<"Nie udalo sie dodac elementu: "<<a.elem<<std::endl;
    }
};

Which worked fine. So my question is

  • Why does the << operator work for the "Element" class and not for the exception class and how can i make it work (I'm not so fond on defining functions inside header file)?
Szymek
  • 1
  • You are not using `U` at all? Why the template? – mch Nov 18 '21 at 21:19
  • I strongly suggest reviewing [this question](https://stackoverflow.com/questions/4660123/overloading-friend-operator-for-template-class), and more specifically, [this answer](https://stackoverflow.com/a/4661372/1322972) – WhozCraig Nov 18 '21 at 21:25
  • Otherwise it shows `friend declaration declares a non-template function` error and among the other things that I tried only this solution worked. – Szymek Nov 18 '21 at 21:27
  • @WhozCraig Thank you, my error was that i misunderstood the `template` purpouse. Now everything works fine. – Szymek Nov 18 '21 at 21:37

0 Answers0