模板和重载istream

时间:2014-01-29 08:14:23

标签: c++ templates friend

我不知道在尝试重载>>时出了什么问题和<<

template<class T, int N> class vector{
    friend istream &operator>> <T,N>(istream &, vector &);
    friend ostream &operator<< <T,N>(ostream &, const vector &);
};

template<class T, int N>
istream &operator>>(istream &input, vector<T,N>& v)
{
    for (int i=0; i<N; i++)
        input >> v.component[i];
    return input;
}

g ++编译器说

vector.h:22:17: error: template-id ‘operator>><double, 2>’ for 
‘std::istream& operator>>(std::istream&, vector<double, 2>&)’ 
does not match any template declaration
friend istream &operator>> <T,N>(istream &, vector &);
             ^
vector.h:23:17: error: template-id ‘operator<< <double, 2>’ for
‘std::ostream& operator<<(std::ostream&, const vector<double, 2>&)’
does not match any template declaration
friend ostream &operator<< <T,N>(ostream &, const vector &);
             ^

2 个答案:

答案 0 :(得分:1)

你需要在模板成为朋友之前声明模板(即,friend子句不能像为函数那样声明模板)。

template<class T, int N> class vector;
template<class T, int N>
istream &operator>>(istream &input, vector<T,N>& v);
template<class T, int N>
ostream &operator<<(ostream &input, vector<T,N> const& v);

template<class T, int N> class vector{
    friend istream &operator>> <T,N>(istream &, vector &);
    friend ostream &operator<< <T,N>(ostream &, const vector &);
};

template<class T, int N>
istream &operator>>(istream &input, vector<T,N>& v)
{
    for (int i=0; i<N; i++)
        input >> v.component[i];
    return input;
}

答案 1 :(得分:0)

您编写重载的方式表示函数模板特化。因此错误,因为没有先前声明的主模板。如果这是主要定义( ),则只需要封闭类声明中的模板参数,因为当您使用类名作为参数时,它们会被强制执行:

template<class T, int N> class vector {
    friend istream &operator>> (istream &, vector &);
    friend ostream &operator<< (ostream &, const vector &);
};

这仅适用于函数的类内声明。您还可以接受不同类型和值的模板参数:

template<class T, int N> class vector {
    template<class T2, int N2>
    friend istream &operator>> (istream &, vector<T2, N2> &);

    template<class T2, int N2>
    friend ostream &operator<< (ostream &, const vector<T2, N2> &);
};