使用模板相关类型在 C++ 中重载运算符“<<”

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

我正在尝试重载“<<”运算符,以便打印已在模板 class 内声明的 class。我一直在寻找解决方案,但我还没有真正找到任何与我自己的相似的例子。以下代码说明了我的问题:

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

您的代码有错误。

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

operator<<的定义移动到dependent_class的范围内,并删除声明前的template<class T>

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