Search code examples
c++oopruntimetemplate-classes

Is there any way to print template class object


I am trying to create template class for storing different values, for instance, I have a list, which can hold value of any type.

template<class T>
class LinkedNode
{
private:
    LinkedNode* next;
    LinkedNode* previous;
    T data;

Is there any way to print value of data. Or in some way specify that T type should have print method. I a little bit confused, because I came from Java. In Java every class is inherited from Object that has toString() method. How can I print value of T type that will be only resolved in runtime.
What is solution in C++ ? Or I have to use some class as base class (virtual) that will have desired method.
I would be grateful for any help.


Solution

  • You need to define your << operator

    std::ostream& operator<<(std::ostream& os, LinkedNode const& node)
    {
        return os << node.data;
    }
    

    This would require that whatever type T is has << defined.