2014-10-17 43 views
8

這極小的例子將無法編譯,因爲A<int>不能A<double>如何讓方法訪問其他模板類實例的私有成員?

template <class T> 
class A { 
    int i; 
    public: 
    template <class U> 
    void copy_i_from(const A<U> & a){ 
     i = a.i; 
    } 
}; 

int main(void) { 
    A<int> ai; 
    A<double> ad; 
    ai.copy_i_from(ad); 
    return 0; 
} 

訪問私有成員i我知道,我可以讓對方(見:How to access private members of other template class instances?)的所有模板實例朋友,但因爲我只有一種方法需要訪問權限(如示例中所示),我寧願將友誼限制爲該方法。這可能嗎?

+1

致敬:我想知道我能做些什麼來改善問題! – DarioP 2014-10-17 10:26:22

+0

這兩個答案和問題本身都默默地降低了;我懷疑它與內容無關。 – Angew 2014-10-17 10:35:50

回答

8

是的,這是可能的。會員功能通常可以指定爲朋友。

template <class T> 
class A { 
    int i; 
    public: 
    template <class U> 
    void copy_i_from(const A<U> & a){ 
     i = a.i; 
    } 
    template <class F> 
    template <class U> 
    friend void A<F>::copy_i_from(const A<U> & a); 
}; 

int main(void) { 
    A<int> ai; 
    A<double> ad; 
    ai.copy_i_from(ad); 
    return 0; 
} 

Live example (gcc one Ideone)


注意,與海灣合作委員會,clang rejects the code。儘管如此,我無法在標準中找到任何會使其失效的內容。

+0

這就是我的嘗試,但它不起作用(不downvoter) – jrok 2014-10-17 10:06:51

+0

@jrok適用於我(呃,對於Ideone GGC)。 – Angew 2014-10-17 10:07:36

+0

@PiotrS。那麼爲什麼沒有「朋友」聲明它不工作?我測試了這一點。 – Angew 2014-10-17 10:08:25

6

看來,如果你想有一個朋友的成員函數,下面將不clang工作:

template <class T> 
class A { 
    int i; 
    public: 
    template <class U> 
    void copy_i_from(const A<U> & a){ 
     i = a.i; 
    } 
    template <class F> 
    template <class U> friend void A<F>::copy_i_from(const A<U> & a); 
}; 

int main(void) { 
    A<int> ai; 
    A<double> ad; 
    ai.copy_i_from(ad); 
    return 0; 
} 

it works on gcc

這個問題似乎是一個clang的代表朋友類模板的問題,其中依賴名稱說明符無法在AST中解析:http://llvm.org/klaus/clang/commit/8b0fa5241a0416fc50dfbb7e38f20e777f191848/(在編寫本文時仍處於中繼狀態)。

因此,你可以去上面的成員函數版本,雖然它可能無法在clang上工作,直到這是想通了。

一個計劃-B的解決辦法是將它免費模板友元函數,雖然它可能不是你想要的(雙方cland和gcc接受):

#include <iostream> 
using namespace std; 

template <class T> 
class A { 
    int i; 
public: 
    template<class V, class U> 
    friend void copy_i_from(A<V>& t, const A<U> & a); 
}; 

template<class V, class U> 
void copy_i_from(A<V>& t, const A<U> & a){ 
    t.i = a.i; 
} 

int main(void) { 
    A<int> ai; 
    A<double> ad; 
    copy_i_from(ai,ad); 
    return 0; 
} 

Example

+1

我認爲即使在編輯之前這是一個有價值的答案(當我刪除它時,我感覺不好),但現在更好! – DarioP 2014-10-17 10:52:09

相關問題