简体   繁体   中英

How do I befriend a template class in a parent namespace?

I'm struggling to make my class be a friend of a template in its parent namespace. Can someone explain what I'm doing wrong:

Here are my attempts and their errors with MSVC8 (Visual Studio 2005):


namespace a {
namespace b {

    template<typename T>
    class x;

    namespace c {

        class y
        {
            template<typename T>
            friend class x;
            ...
        };

    }
}}

error C2888: a::b::x : symbol cannot be defined within namespace c


namespace a {
namespace b {

    template<typename T>
    class x;

    namespace c {

        class y
        {
            template<typename T>
            friend class ::a::b::x;
            ...
        };

    }
}}

error C2888: a::b::x : symbol cannot be defined within namespace c


namespace a {
namespace b {

    namespace c {

        class y
        {
            template<typename T>
            friend class ::a::b::x;
            ...
        };

    }
}}

error C2039: x : is not a member of a::b


I can't just include the header file containing class x as it depends on class y leading to a circular inclusion.

A hack workaround: If you know the all specific types the template will ever be instantiated with, befriend each instantiation rather than the template. For example:

namespace a {
namespace b {

    template<typename T>
    class x;

    namespace c {

        class y
        {
            friend class x<char>;
            friend class x<wchar_t>;
            ...
        };

    }
}}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM