具有流运算符重载的模板 Class

Template Class with stream operator overloading

我想更好地了解一些C++的高级职员。我现在正在尝试理解 stream operator overloadingfriend functiontemplate 。我试图在一个代码段中学习所有这些东西。

所以,我正在尝试实现一个 template class,它只包含一个 array,我想用 stream operator 填充它。所以,我想到了这个。

#include <iostream>
using namespace std;

template<class T, int L>
class TestClass
{
    private:
        T data[L];
    public:
        friend void operator>>(const istream&, const TestClass<T,L>&);
};

template<class T, int L>
void operator>>(const istream& in, const TestClass<T,L>& q)
{
    for(int i = 0; i < L; i++)
    {
        in >> q.data[i];
    }
}

int main() {
    TestClass<float, 3> Q;
    cin >> Q;

    return 0;
}

这是非常简单的代码段。但是,我在编译时遇到以下错误

undefined reference to `operator>>(std::istream const&, TestClass<float, 3> const&)'

带有以下警告

warning: friend declaration 'void operator>>(const istream&, const TestClass<T, L>&)' declares a non-template function [-Wnon-template-friend]|

我知道,我犯了一些菜鸟错误,因为我对这件事还很陌生。如果有人帮助 运行 成功,那就太好了。

问题有两个方面:

  1. 你的friend函数也应该是一个模板
  2. 您将 istreamTestClass 作为常量传递。删除那个

这是更新后的代码:

template<class T, int L>
class TestClass
{
    private:
        T data[L];
    public:
        template<class U, int M>
        friend void operator>>(istream&, TestClass<U,M>&);
};

template<class T, int L>
void operator>>(istream& in, TestClass<T,L>& q)
{
    for(int i = 0; i < L; i++)
    {
        in >> q.data[i];
    }
}

Demo


编辑:其他同样有效的方法

声明好友的语法略有不同,一切正常Demo

template<class T, int L>
class TestClass
{
    private:
        T data[L];
    public:
        friend void operator>> <>(istream&, TestClass&);
};

(感谢@chris)。此格式(带有 <>)与上述示例的不同之处在于,上述示例在技术上将 operator>>all 实例声明为 friend 而这个只有一对一的关系。

或者您可以在友元声明中包含定义 Demo:

template<class T, int L>
class TestClass
{
    private:
        T data[L];
    public:
        friend void operator>>(istream& in, TestClass& q){
            for(int i = 0; i < L; i++)
            {
                in >> q.data[i];
            }       
        }
};