Output a nested class inside a template

梦想与她 提交于 2019-12-23 10:42:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/4351567/output-a-nested-class-inside-a-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!