首页 > 编程语言 > 详细

gcc的bug? c++模板类中友元函数的访问权限问题

时间:2014-04-20 18:47:55      阅读:511      评论:0      收藏:0      [点我收藏+]

原文地址: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.csdn.net/songyuanyao]
********************************************************************/


gcc的bug? c++模板类中友元函数的访问权限问题,布布扣,bubuko.com

gcc的bug? c++模板类中友元函数的访问权限问题

原文:http://blog.csdn.net/yaosongyuan/article/details/24174549

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!