8

In C++03 the following is illegal, although some compilers support it.

template <class T>
class X
{
    friend T;
};

Has this been legalized in C++11? (Sorry, didn't have time to read the draft myself, just hoping someone knows this)

Xeo
  • 129,499
  • 52
  • 291
  • 397
Armen Tsirunyan
  • 130,161
  • 59
  • 324
  • 434

3 Answers3

13

From section §11.3, 3 in N3291:

template <typename T> class R {
  friend T;
};

R<C> rc; // class C is a friend of R<C>
R<int> Ri; // OK: "friend int;" is ignored

So it is legal in C++11.

Praetorian
  • 106,671
  • 19
  • 240
  • 328
1

Yes c++0x allows template parameter to be friends.

Well, I happened to remember read it in the draft before but could not find the reference..anyways @Praetorian's answer nailed it.

sehe
  • 374,641
  • 47
  • 450
  • 633
Alok Save
  • 202,538
  • 53
  • 430
  • 533
0

It is illegal in plain C++, but there is a simple workaround

template <class T>
class X
{
    private:
        class Wrapper
        {
            public:
                typedef T Type;
        };
        friend class Wrapper::Type;
};
Frigo
  • 1,709
  • 1
  • 14
  • 32
  • Works on gcc but not on VC2010 and Comeau – Sumant Sep 28 '11 at 22:49
  • Yeah, tried it on Clang as well, didn't work :( - Apparently the standard forbids befriending typedef'd types which the GCC does not check for. However it is permitted to write `friend T;` which GCC does not recognize, but Clang does. – Frigo Sep 28 '11 at 23:27