原文地址:http://stackoverflow.com/q/23171337/3309790
在c++中,模板类中可以直接定义一个友元函数,该函数拥有访问该模板类非public成员的权限。比如:
#include <iostream>
using namespace std;
template <typename T>
class template_class {
T v;
friend void foo(template_class t) {
t.v = 1; // (1)可以访问私有成员因为是友元函数
cout << t.v << endl;
template_class<int> t1;
t1.v = 2; // (2)可以访问私有成员如果以[T=int]实例化
cout << t1.v << endl;
template_class<char> t2;
t2.v = 'c'; // (3)不可以访问私有成员如果以[T=int]实例化
cout << t2.v << endl;
}
};
int main() {
template_class<int> t; //(4)产生(实例化)void foo(template_class<int> t)
foo(t);
return 0;
}
(4)产生(实例化)出函数void foo(template_class<int>)的定义,并且使得它成为
template_class<int>的友元,所以它可以访问
template_class<int>的私有成员,正如
(1)和(2)所做的。但是(3)应该不可以,因为它并不是template_class<char>的友元,只有
void foo(template_class<char>)是
template_class<char>的友元。
但是这段source可以在 gcc 4.8.1上编译通过,但是在clang 3.4编译失败。为什么?这只是一个gcc的bug吗?c++标准对此有明确规定吗?
* 不落魄的书生的记事簿[blog.youkuaiyun.com/songyuanyao]
********************************************************************/