How to define a friend function declared in a class without a template inside a template class outside both classes?

I found a "how to define a template class friend function template is its announcement" ( qaru.site/questions/1019738 / ... / cppreference ), but how to do it, if we add another inner class template is not in the mix?

those. how to (externally) determine operator<<declared in class Internal, from the following example:

#include <iostream>

template <typename T>
class External {
public:
    explicit External(T initial) : value{initial} {}
    class Internal {
    public:
        Internal(const External& e) : internal_value{e.value} {}

    private:        
        friend std::ostream& operator<<(std::ostream& os, const Internal& i);
        // ^^^ this one
        /* body
        {
            return os << i.internal_value;
        }
        */

        T internal_value;
    };

    friend std::ostream& operator<<(std::ostream& os, const External& e)
    {
        return os << Internal{e};
    }
private:
    T value;
};

int main()
{
    std::cout << External<int>{5};
}
+6
source share
1 answer

. , External , Internal . . , .

, . , . , .

, :

std::ostream& operator<<(std::ostream& os, External<int>::Internal const& i)
{
    return os << i.internal_value;
}

. , , .

, . External . , inline, - ( ):

class Internal {
public:
    Internal(const External& e) : internal_value{e.value} {}

private:
    std::ostream& print(std::ostream&) const;
    friend std::ostream& operator<<(std::ostream& os, Internal const& i)
    {
        return i.print(os); // Short and sweet on account of being inline
    }

    T internal_value;
};

//....

template<typename T>
std::ostream& External<T>::Internal::print(std::ostream& os) const {
   // Provided outside of the class definition, can be as verbose as you like
   return os << internal_value;
}
+6

All Articles