friend T

template<typename Host>
class Foo
{
  friend Host; // g++ 不能編譯
};


樓主撞上敏感問題了,根據現行 C++03 標準,你的寫法是明確禁止的,參見標準 7.1.5.3/2 (注意其中紅色部分)

3.4.4 describes how name lookup proceeds for the identifier in an elaborated-type-specifier. If the identifier resolves to a class-name or enum-name, the elaborated-type-specifier introduces it into the declaration the same way a simple-type-specifier introduces its type-name. If the identifier resolves to a typedef-name or a template type-parameter, the elaborated-type-specifier is ill-formed. [Note: this implies that, within a class template with a template type-parameter T, the declaration
  friend class T;
  is ill-formed. ] If name lookup does not find a declaration for the name, the elaborated-type-specifier is ill-formed unless it is of the simple form class-key identifier in which case the identifier is declared as described in 3.3.1.

有趣的是正在審議的新版標準 c++0x,對此有不同的解釋,參見 n3126,7.1.6.3/2 (注意紅色部分)

3.4.4 describes how name lookup proceeds for the identifier in an elaborated-type-specifier. If the identifier resolves to a class-name or enum-name, the elaborated-type-specifier introduces it into the declaration the same way a simple-type-specifier introduces its type-name. If the identifier resolves to a typedef-name, the elaborated-type-specifier is ill-formed. [ Note: this implies that, within a class template with a template type-parameter T, the declaration
  friend class T;
is ill-formed. However, the similar declaration friend T; is allowed (11.4). — end note ]


#include<iostream>



using namespace std;


template<typename T>
class identity {
public:
typedef T me;
};


template<typename my_friend>

class Foo {
private:
friend class identity<my_friend>::me;
int i, j;
void show() {
cout << "Foo show" << endl;
}
;
};


class A {
Foo<A> fa;
public:
void seti(int i) {
fa.i = i;//A作爲Foo<A>的友元訪問其私有成員變量
}
;
};


class B {
public:
static void show(Foo<B> &fb) {
fb.show();//B作爲Foo<B>的原有訪問其私有函數
}
};
int main(int argc, char** argv) {
A a;
a.seti(0);
B b;
Foo<B> fb;
b.show(fb);
return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章