问题
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)
回答1:
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.
回答2:
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.
回答3:
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;
};
来源:https://stackoverflow.com/questions/6510041/template-parameter-as-a-friend