Template parameter as a friend

橙三吉。 提交于 2019-12-30 06:18:11

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!