guyoverthere522
guyoverthere522

Reputation: 33

Overloading operator "<<" in C++ with template-dependent type

I'm trying to overload the "<<" operator in order to print a class that has been declared inside a template class. I've looked for a solution but I haven't really found any examples similar to my own. The following code illustrates my problem:

#include <iostream>

template<class T>
class main_class
{
public:
    class dependent_class
    {
    public:
        dependent_class() : val(0) { }
        template<class T>
        friend std::ostream& operator<<(std::ostream&, const dependent_class&);
    protected:
        int val;
    };
};

template<class T>
std::ostream& operator<<(std::ostream& out, const typename main_class<T>::dependent_class& v)
{
    return out << v.val;
}

int main(int argc, char* argv[])
{
    main_class<int>::dependent_class v;
    std::cout << v; // error: no operator "<<" matches these operands
    //      operand types are: std::ostream << main_class<int>::dependent_class

    return 0;
}

Upvotes: 3

Views: 210

Answers (2)

Amal K
Amal K

Reputation: 4899

Move the definition of operator<< to the scope of dependent_class and remove template<class T> before the declaration:

#include <iostream>

template<class T>
class main_class
{
public:
    class dependent_class
    {
    public:
        dependent_class() : val(0) { }
        friend std::ostream& operator<<(std::ostream& out, const dependent_class& v)
        {
            return out << v.val;
        }

    protected:
        int val;
    };
};




int main(int argc, char* argv[])
{
    main_class<int>::dependent_class v;
    std::cout << v; // error: no operator "<<" matches these operands
    //      operand types are: std::ostream << main_class<int>::dependent_class

    return 0;
}

Upvotes: 0

user10057478
user10057478

Reputation:

#include <iostream>

template<class T>
class main_class
{
public:
    class dependent_class
    {
    public:
        dependent_class() : val(0) { }

        friend std::ostream& operator<<(std::ostream& out, const main_class<T>::dependent_class& v){
            return out << v.val;
        }
    protected:
        int val;
    };
};



int main(int argc, char* argv[])
{
    main_class<int>::dependent_class v;
    std::cout << v; // error: no operator "<<" matches these operands
    //      operand types are: std::ostream << main_class<int>::dependent_class

    return 0;
}

You were having errors in your code.

In the dependent_class you are using the template twice which shadows the template parameter.

 class dependent_class
    {
    public:
        dependent_class() : val(0) { }
        template<class T> //here
        friend std::ostream& operator<<(std::ostream&, const dependent_class&);
    protected:
        int val;
    };

Upvotes: 1

Related Questions