我试图将模板类的模板成员函数的声明和定义分开,但最终出现以下错误和警告。
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;
}
当我加入这样的声明和定义时,一切都可以编译。
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;
}
};
目的是将成员变量_integers打印到cout。可能是什么问题?
附注:我使用this question释放了该函数,但并没有帮助。
最佳答案
BigUnsigned
是模板类型,因此
std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu)
由于没有
BigUnsigned
,因此无法使用。您需要使friend function成为模板,以便可以采用不同类型的BigUnsigned<some_type>
。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;
}
第二个示例起作用的原因是,由于它是在类内部声明的,因此它使用该类使用的模板类型。
关于c++ - 运算符<<(ostream&,const BigUnsigned <I>&)必须正好采用一个参数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34928076/