gcc的错误?模板类中friend函数的访问控制问题 [英] Bug of gcc? Access control issue about friend function in template class

查看:28
本文介绍了gcc的错误?模板类中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),并使其成为template_class的友元,所以它可以访问 template_class 的私有成员,如上述源代码中的 (1) 和 (2).但是(3)也应该不行,它不是template_class的朋友,只有void foo(template_class<char>)会是template_class.

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 编译正常,但clang 3.4.那么哪个是正确的呢?这只是gcc的一个错误吗?标准是否对这种情况有明确的定义?

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 错误.PR 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆