Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output a nested class inside a template

I'm trying to overload the ostream operator to allow output for a nested class inside a template. However, the compiler is unable to bind the actual function call to my overload.

template <class T>
struct foo
{
    struct bar { };
};

template <class T>
std::ostream& operator << (std::ostream& os, 
    const typename foo<T>::bar& b)
{
    return os;
}

int main()
{
    foo<int>::bar b;
    std::cout << b << std::endl; // fails to compile
}

This will compile if I define the overload as an inline friend function:

template <class T>
struct foo
{
    struct bar 
    { 
        friend std::ostream& operator << (std::ostream& os, const bar& b)
        {
            return os;
        }
    };
};

But I'd rather define the overload outside of the class. Is this possible?

like image 210
Channel72 Avatar asked Nov 15 '22 05:11

Channel72


1 Answers

No. :-) You have already answered your own question, but somehow you don't like the answer? Johannes links to a post that explains that the inner class is a "non-deduced context". If there are some specializations of the foo template, there might be several foos with the same inner bar class. The compiler can then not figure out what foo::bar is, unless it instantiated foo for all possible Ts. The standard says that it doesn't have to do that.

What's wrong with your original solution with a friend operator? You don't have to define it inline, you just have to declare it inside the local class.

like image 57
Bo Persson Avatar answered Dec 11 '22 08:12

Bo Persson