2016-04-24 55 views
1

这里是我的代码:如何告诉编译器我的朋友的功能是函数模板

#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 
} 

我只是想简单的<>符号告诉编译器我的函数是函数模板。但我得到两行错误:朋友只能是类或功能

friend bool operator== <> (const stack<T, Sequence>&, const stack<T, Sequence> &); 
friend bool operator< <> (const stack<T, Sequence>&, const stack<T, Sequence>&); 

我该怎么做才能解决它。

回答

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和第二比序列不同,否则你会被遮蔽的类的模板参数。

+0

是的,它的工作原理!谢谢〜 – Superxy