2

我试图给我的班级写一个朋友运算符<<,但我收到了这个冗余警告。并且无法弄清楚如何解决它。

先感谢您。

#include <iostream>
using namespace std;

template<class  T>
class test
{
public:
    explicit test(T a)  noexcept : m_{ a } {}
    template <class Y>

    //line below shows that warning.
    friend std::ostream& operator<<(std::ostream& out, const test<Y>& lhs);
private:
    T m_;
};

template<class Y>
std::ostream& operator<<(std::ostream& out, const test<Y>& lhs)
{
    out << lhs.m_ << endl;
    return out;
}


int main()
{
    test<int>    p {25};
    test<double> q {17.5};

    std::cout << "By Friend " << p;
    std::cout << "By Friend " << q;
    return 0;
}

Edit 1 //Removed template Y from operator<< int he class declaration

template<class  T>
class test
{
public:
    explicit test(T a)  noexcept : m_{ a } {}
    friend std::ostream& operator<< (std::ostream&, const test<T>&);
private:
    T m_;
};

template<class T>
std::ostream& operator<<(std::ostream& out, const test<T>& lhs)
{
    out << lhs.m_ << endl;
    return out;
}

现在我收到了警告

警告:朋友声明 'std::ostream& operator<<(std::ostream&, const test&)' 声明了一个非模板函数 [-Wnon-template-friend]

PS:在 Visual Studio 中我得到了错误链接

EDIT 1.2 //编辑完成EDIT 1

我将编辑 1 更改如下:

....
friend std::ostream& operator<< <> (std::ostream&, const test<T>&);
....

因此警告和错误链接得到解决。

4

0 回答 0