c++templatesnamespacesvisual-studio-2005visual-c++-2005

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.


Solution

  • 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>;
                ...
            };
    
        }
    }}