2016-05-15 75 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