Bug of gcc? Access control issue about friend function in template class

邮差的信 提交于 2019-12-11 03:41:53

问题


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;
}

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>.

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?


回答1:


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.



来源:https://stackoverflow.com/questions/23171337/bug-of-gcc-access-control-issue-about-friend-function-in-template-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!