• 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]
    ********************************************************************/
    
  • 相关阅读:
    SQL性能优化思路
    EF Migraiton错误解决
    How to resolve the 403 error when send POST request from Postman
    Disable trigger to avoid the ID is auto-updated
    MBG(Mybatis Generator)配置
    Publish Web Site To IIS From VS
    quickSort算法导论版实现
    Clang与libc++abi库安装
    Clang与libc++abi库安装
    整数中1 的个数
  • 原文地址:https://www.cnblogs.com/mengfanrong/p/5158643.html
Copyright © 2020-2023  润新知