2016-05-15 67 views
4

我有一个需要访问其专用字段的类模板和运营商模板。我可以做一个模板朋友:运营商的朋友特定模板实例化

template <typename T> 
class A { 
    int x; 
    template <typename U> 
    friend bool operator==(const A<U>& a, const A<U>& b); 
}; 

template <typename T> 
bool operator== (const A<T>& a, const A<T>& b) { 
    return a.x == b.x; 
} 

int main() { 
    A<int> x, y; 
    x == y; 
    return 0; 
} 

但有可能仅使operator==<T>的朋友A<T>,而不是使operator==<int>朋友A<double>

回答

6

如果friend有问题,请在定义A类之前将声明前移。

template <typename T> 
bool operator== (const A<T>& a, const A<T>& b); 

那么你可以更清楚地friend。完整的解决方案(ideone):

template <typename T> 
class A; 

// declare operator== early (requires that A be introduced above) 
template <typename T> 
bool operator== (const A<T>& a, const A<T>& b); 

// define A 
template <typename T> 
class A { 
    int x; 
    // friend the <T> instantiation 
    friend bool operator==<T>(const A<T>& a, const A<T>& b); 
}; 

// define operator== 
template <typename T> 
bool operator== (const A<T>& a, const A<T>& b) { 
    return a.x == b.x; 
} 
2

是的,你可以。语法如下:

template <typename T> 
class A { 
    int x; 
    friend bool operator==<>(const A& a, const A& b); 
}; 

而且A上课前把你operator==定义(或只是一个声明)。

+2

似乎并没有工作http://ideone.com/vnu3QR – RiaD

+0

这不是一个编译器错误。有些地方的语法是有效的,但这不是其中之一。 –

+0

@AlanStokes,好吧,是的,这个语法在这里完全有效。你为什么不试试自己?只需在课程前加上'operator =='即可。 – ixSci