朋友运营商<<在模板类中

时间:2014-08-09 09:47:12

标签: c++ templates friend

根据我对朋友功能的了解,这应该有效。我不知道发生了什么。

在我的代码中,我定义了一个类

template < class IType = unsigned int >
class BitArray {
    ...
    friend ostream& operator<<(ostream&, const BitArray&);
    friend istream& operator>>(istream&, BitArray&);
    ...
}

然后在同一个头文件中

template < class IType >
ostream& operator<<(ostream& os, const BitArray<IType>& that)
{
    ...
}

template < class IType >
istream& operator>>(istream& is, BitArray<IType>& that)
{
    ...
}

它给了我

error LNK2019: unresolved external symbol

当我尝试编译时。

我重新阅读并重写了这六次,并回顾了&#34;朋友&#34;的使用情况。关键字,无法找到错误。

由于模板

,此实现是否遵循不同的规则

我也覆盖了&lt;&lt;和&gt;&gt;作为轮班操作员,但由于他们有不同的论点,这不应该是重要的;

2 个答案:

答案 0 :(得分:1)

警告,你有:

warning: friend declaration 'std::ostream& operator<<(std::ostream&, const BitArray<IType>&)' declares a non-template function [-Wnon-template-friend]
note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)

所以在声明模板函数之前:

template <class IType> class BitArray;
template <class IType> std::ostream& operator<<(std::ostream&, const BitArray<IType>&);
template <class IType> std::istream& operator>>(std::istream&, BitArray<IType>&);

template < class IType = unsigned int >
class BitArray {
    friend std::ostream& operator<< <>(std::ostream&, const BitArray&);
    friend std::istream& operator>> <>(std::istream&, BitArray&);
};

template <class IType>
std::ostream& operator<<(std::ostream& os, const BitArray<IType>& b)
{
    /* Your implementation */
}

Live example

答案 1 :(得分:0)

我想你想要这个:

template < class IType = unsigned int >
class BitArray {
    template<class> friend ostream& operator<<(ostream&, const BitArray&);
    template<class> friend istream& operator>>(istream&, BitArray&);
};

你的BitArray声明告诉编译器寻找一个非模板化的运算符&lt;&lt;和运算符&gt;&gt;