2

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

#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>),并使其成为 的朋友,这样它就可以访问上述源中的(1)和(2)template_class<int>的私有成员。template_class<int>但是(3)也应该不行,它不是 的朋友template_class<char>,只会void foo(template_class<char>)是 的朋友template_class<char>

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

4

1 回答 1

1

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

于 2014-12-27T21:06:46.817 回答