我有一个模板类,我在类中定义了一个友元函数。
#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)生成函数void foo(template_class<int>)
, 并使其成为 template_class<int>
的好友, 所以它可以访问 template_class<int>
的私有(private)成员就像上面源代码中的 (1) 和 (2)。但是(3)也不行,它不是template_class<char>
的 friend , 只有 void foo(template_class<char>)
将成为template_class<char>
的 friend .
编辑 正如@Constructor 和@Chnossos 所说,上面的源代码使用gcc 4.8.1 编译成功。 , 但因 clang 3.4 而失败.那么哪个是正确的呢?这只是gcc的一个错误吗?标准对这种情况有明确的定义吗?
最佳答案
关于c++ - 海湾合作委员会的错误?关于模板类中友元函数的访问控制问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23171337/