Search code examples
c++templatesfriend

Friending a dependent template class


I have a case in my code where I need to make a dependent template class a friend, but I think I've exhausted the possibilities and none of them work. Is this possible to do at all? If so, how?

Simplest example:

struct Traits {
    template <typename T>
    struct Foo {
        typedef typename T::bar* type;
    };
};

template <typename T>
class Bar
{
    typedef int bar;
    // need to make T::Foo<Bar> a friend somehow?
    typedef typename T::template Foo<Bar>::type type; // won't compile because bar is private... 
                                                      // suppose I cannot make bar public.


    type val;
};

int main() {
    Bar<Traits> b;
}

Solution

  • struct Traits {
        template <typename T>
        struct Foo {
            typedef typename T::bar* type;
        };
    };
    
    template <typename T>
    class Bar
    {
        typedef int bar;
        friend typename T::template Foo<Bar>;
        typedef typename T::template Foo<Bar>::type type;
        type val;
    };
    
    int main() {
        Bar<Traits> b;
    }