Question

I have a template class, and I define a friend function inside the class.

#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;
}

If my understanding is correct, (4) generate the function void foo(template_class<int>), and make it the friend of template_class<int>, so it can access the private member of template_class<int> like (1) and (2) in above source. But (3) should not be OK too, it's not the friend of template_class<char>, only void foo(template_class<char>) will be the friend of template_class<char>.

EDIT As @Constructor and @Chnossos said, The above source compiled OK with gcc 4.8.1, but failed with clang 3.4. So which one is correct? Is it just a bug of gcc? Does the standard has an explicit definition about this case?

Was it helpful?

Solution

As dyp says in the comments, this is simply a GCC bug. Either PR 41437 or one of the others that PR 59002 links to.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top