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

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


转载于:https://www.cnblogs.com/mengfanrong/p/5158643.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值