テンプレート クラスがあり、クラス内でフレンド関数を定義します。
#include <iostream>
using namespace std;
template <typename T>
class template_class {
T v;
friend void foo(template_class t) {
t.v = 1; // (1)can access the private member because it's a friend
cout << t.v << endl;
template_class<int> t1;
t1.v = 2; // (2)accessible if instantiated with [T=int]
cout << t1.v << endl;
template_class<char> t2;
t2.v = 'c'; // (3)should not be accessible too if instantiated with [T=int]
cout << t2.v << endl;
}
};
int main() {
template_class<int> t; // (4)generate void foo(template_class<int> t)
foo(t);
return 0;
}
私の理解が正しければ、(4) functionvoid foo(template_class<int>)
を生成し、それを のフレンドにすると、上記のソースの (1) や (2)template_class<int>
のようなプライベート メンバーにアクセスできるようになります。template_class<int>
しかし、(3)もOKではありません。 の友達ではなく、 の友達になるtemplate_class<char>
だけです。void foo(template_class<char>)
template_class<char>
編集 @Constructor と @Chnossos が言ったように、上記のソースはgcc 4.8.1で問題なくコンパイルされましたが、 clang 3.4で失敗しました。それで、どれが正しいですか?それはgccの単なるバグですか?標準には、このケースについて明示的な定義がありますか?