gcc的错误?模板类中的friend函数的访问控制问题 [英] Bug of gcc? Access control issue about friend function in template class
问题描述
我有一个模板类,并在类中定义了一个friend函数。
I have a template class, and I define a friend function inside the class.
#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>
like(1)和(2)。但是(3)不应该也是好的,它不是 template_class< char>
的朋友,只有 void foo(template_class< char>)
将是
template_class< char>
的朋友。
If my understanding is correct, (4) generate the function void foo(template_class<int>)
, and make it the friend of template_class<int>
, so it can access the private member of template_class<int>
like (1) and (2) in above source. But (3) should not be OK too, it's not the friend of template_class<char>
, only void foo(template_class<char>)
will be the friend of template_class<char>
.
>
由于@Constructor和@Chnossos表示,上述源码使用 gcc 4.8.1 编译为OK,但是失败,并 clang 3.4 。那么哪一个是正确的呢?这只是一个gcc的bug?
EDIT As @Constructor and @Chnossos said, The above source compiled OK with gcc 4.8.1, but failed with clang 3.4. So which one is correct? Is it just a bug of gcc? Does the standard has an explicit definition about this case?
推荐答案
正如dyp在注释中说的,这只是一个GCC错误。 公关41437 或其他人之一 PR 59002 链接到。
As dyp says in the comments, this is simply a GCC bug. Either PR 41437 or one of the others that PR 59002 links to.
这篇关于gcc的错误?模板类中的friend函数的访问控制问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!