c – 需要前向声明的嵌套类中的朋友声明

我试图为私有成员的嵌套类编写非侵入式boost :: serialization例程.不幸的是,我没有说服g序列化例程是内部类的朋友.似乎g需要序列化例程的前向声明,而后者又需要嵌套类的前向声明,而后者又不能在C中完成.我错过了什么,或者这是不可能的?相反,clang不需要前向声明,并且对下面的代码没有任何问题.以下代码说明了该问题:

#include <boost/archive/text_oarchive.hpp>

class Outer;
//class Outer::Inner;   // Not valid C++

namespace boost
{
    namespace serialization
    {
        template <class Archive>
        void serialize(Archive &ar, Outer& outer, const unsigned int version);
        //template <class Archive>
        //void serialize(Archive &ar, Outer::Inner& inner, const unsigned int version); // Cannot be done since forward declaration of nested class not possible.
    }
}

class Outer
{
    class Inner
    {
        int member_{42};

        template <class Archive>
        friend void boost::serialization::serialize(Archive &ar, Outer::Inner &inner, const unsigned int version);  // This does not work with gcc since the compiler seems to expect a forward declaration, which cannot be done (see above).
    };

    Inner inner_;

    template <class Archive>
    friend void boost::serialization::serialize(Archive &ar, Outer &outer, const unsigned int version);
    template <class Archive>
    friend void boost::serialization::serialize(Archive &ar, Inner &inner, const unsigned int version);
};

namespace boost
{
    namespace serialization
    {
        template <class Archive>
        void serialize(Archive &ar, Outer& outer, const unsigned int version)
        {
            ar & outer.inner_;
        }

        template <class Archive>
        void serialize(Archive &ar, Outer::Inner& inner, const unsigned int version)
        {
            ar & inner.member_;
        }
    }
}

int main()
{
    Outer outer;

    boost::archive::text_oarchive(std::cout) << outer;
}

要使用-std = c 11和-lboost_serialization进行编译.使用g编译抱怨即使朋友声明存在,member_也是私有的.是否正确拒绝内部类中的朋友声明?

最佳答案
[dcl.meaning]/1

When the declarator-id is qualified, the declaration shall refer to
a previously declared member of the class or namespace to which the
qualifier refers
(or, in the case of a namespace, of an element of the
inline namespace set of that namespace ([namespace.def])) or to a
specialization thereof; […].

换句话说,具有限定名称的声明(包括友元声明)必须引用先前声明的内容.因此,GCC在拒绝代码方面是正确的,但它应该早先拒绝它,并且诊断相当混乱. (请注意,如果被联系的东西是以前未声明的普通函数而不是模板,它会在现场拒绝它.)

此外,要求朋友访问类型首先打破了非侵入式序列化的要点(这允许您在不更改其定义的情况下序列化类).

点赞