这是我的代码:
#include <iostream>
#include <cstddef>
class alloc
{
};
template <class T, class Alloc = alloc, size_t BufSiz = 0>
class deque
{
public:
deque() { std::cout << "deque" << std::endl; }
};
template <class T, class Sequence = deque<T> >
class stack
{
public:
stack() { std::cout << "stack" << std::endl; }
private:
Sequence c;
friend bool operator== <> (const stack<T, Sequence>&, const stack<T, Sequence> &);
friend bool operator< <> (const stack<T, Sequence>&, const stack<T, Sequence>&);
};
template <class T, class Sequence>
bool operator== (const stack<T, Sequence>&x, const stack<T, Sequence>&y)
{
return std::cout << "opertor == " << std::endl;
}
template <class T, class Sequence>
bool operator < (const stack<T, Sequence> &x, const stack<T, Sequence> &y)
{
return std::cout << "operator <" << std::endl;
}
int main()
{
stack<int> x; // deque stack
stack<int> y; // deque stack
std::cout << (x == y) << std::endl; // operator == 1
std::cout << (x < y) << std::endl; // operator < 1
}
我只是想一个简单的&lt;&gt;符号告诉编译器我的函数是函数模板。但我得到两行错误:朋友只能是班级或职能
friend bool operator== <> (const stack<T, Sequence>&, const stack<T, Sequence> &);
friend bool operator< <> (const stack<T, Sequence>&, const stack<T, Sequence>&);
我该怎么做才能解决它。
答案 0 :(得分:3)
只需使用以下语法:
template<typename T1, typename Sequence1>
friend bool operator== (const stack<T1, Sequence1>&, const stack<T1, Sequence> &);
template<typename T1, typename Sequence1>
friend bool operator< (const stack<T1, Sequence1>&, const stack<T1, Sequence>&);
第一个模板参数与T不同,第二个模板参数与Sequence不同,或者您将隐藏类的模板参数。