c++ - 海湾合作委员会的错误?关于模板类中友元函数的访问控制问题

标签 c++ templates gcc access-control friend-function

我有一个模板类,我在类中定义了一个友元函数。

#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<int>) , 并使其成为 template_class<int> 的好友, 所以它可以访问 template_class<int> 的私有(private)成员就像上面源代码中的 (1) 和 (2)。但是(3)也不行,它不是template_class<char>的 friend , 只有 void foo(template_class<char>)将成为template_class<char>的 friend .

编辑 正如@Constructor 和@Chnossos 所说,上面的源代码使用gcc 4.8.1 编译成功。 , 但因 clang 3.4 而失败.那么哪个是正确的呢?这只是gcc的一个错误吗?标准对这种情况有明确的定义吗?

最佳答案

正如 dyp 在评论中所说,这只是一个 GCC 错误。 PR 41437或其他人之一 PR 59002链接到。

关于c++ - 海湾合作委员会的错误?关于模板类中友元函数的访问控制问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23171337/

相关文章:

c++ - 无法理解如何摆脱goto

c++ - C++ 中是否有最大数组长度限制?

templates - 在 Go 服务器 : download fail 上加载 Angular2 Bootstrap 模板 ng2-admin

c++ - 在运行时识别模板类型名

c++ - 将 LTO 与 arm-none-eabi 和 newlib-nano 结合使用

c++ - stoi 没有在此范围内声明?

c++ - 在未使用 constexpr 函数的返回值的情况下,g++ 编译器是否将其视为常规函数?

c++ - 可以在重载运算符中使用访问器方法吗?

forms - 使用 Symfony2 在 Twig 模板中渲染表单

c - 使用 fscanf 读取两行整数