operator <<(ostream&,const BigUnsigned <I>&)必须只接受一个参数

Sla*_*zer 2 c++ templates operator-overloading c++11

我试图分离模板化类的模板化成员函数的声明和定义,但最终出现以下错误和警告.

template <typename I>
class BigUnsigned{
    const size_t cell_size=sizeof(I);
    std::vector<I> _integers;
public:
    BigUnsigned();
    BigUnsigned(I);
    friend std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu);
};

std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu){
    for (auto integer : bu._integers){
        out<<integer<<std::endl;
    }
    return out;
}
Run Code Online (Sandbox Code Playgroud)

../hw06/bigunsigned.h:13:77:警告:朋友声明'std :: ostream&operator <<(std :: ostream&,const BigUnsigned&)'声明一个非模板函数[-Wnon-template-friend]的朋友std :: ostream&operator <<(std :: ostream&out,const BigUnsigned&bu); ^ ../hw06/bigunsigned.h:13:77:注意:(如果这不是你想要的,请确保已经声明了函数模板,并在函数名后添加<>)../hw06/bigunsigned .h:16:51:错误:无法使用模板名称'BigUnsigned'而没有参数列表std :: ostream&operator <<(std :: ostream&out,const BigUnsigned&bu){^ ../hw06/bigunsigned.h :在函数'std :: ostream&operator <<(std :: ostream&,const int&)':../ hw06/bigunsigned.h:17:28:error:请求'bu'中的成员'_integers',这是非类型'const int'的表达式(auto integer:bu._integers){^

当我加入这样的声明和定义时,一切都很好.

template <typename I>
class BigUnsigned{
    const size_t cell_size=sizeof(I);
    std::vector<I> _integers;
public:
    BigUnsigned();
    BigUnsigned(I);
    friend std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu){
        for (auto integer : bu._integers){
            out<<integer<<std::endl;
        }
        return out;
    }
};
Run Code Online (Sandbox Code Playgroud)

目的是将成员变量_integers打印到cout.可能是什么问题?

PS:使用这个问题我使这个功能免费,但没有帮助.

Nat*_*ica 7

BigUnsigned 是一个模板类型

std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu)
Run Code Online (Sandbox Code Playgroud)

不行,因为没有BigUnsigned.您需要将朋友功能设为模板,以便您可以使用不同类型的BigUnsigned<some_type>s.

template <typename I>
class BigUnsigned{
    const size_t cell_size=sizeof(I);
    std::vector<I> _integers;
public:
    BigUnsigned();
    BigUnsigned(I);
    template<typename T>
    friend std::ostream& operator<<(std::ostream& out, const BigUnsigned<T>& bu);
};

template<typename T>
std::ostream& operator<<(std::ostream& out, const BigUnsigned<T>& bu){
    for (auto integer : bu._integers){
        out<<integer<<std::endl;
    }
    return out;
}
Run Code Online (Sandbox Code Playgroud)

第二个示例的工作原理是,因为它在类中声明,所以它使用类使用的模板类型.