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)?