在模板中输出嵌套类

Cha*_*l72 5 c++ templates iostream

我正在尝试重载ostream运算符以允许输出模板内的嵌套类.但是,编译器无法将实际函数调用绑定到我的重载.

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
}
Run Code Online (Sandbox Code Playgroud)

如果我将重载定义为内联friend函数,这将编译:

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

但我宁愿在课外定义重载.这可能吗?

Bo *_*son 1

不。:-) 您已经回答了自己的问题,但不知何故您不喜欢这个答案?Johannes 链接到一篇文章,解释内部类是“非推导的上下文”。如果 foo 模板有一些特殊化,则可能有多个 foo 具有相同的内部 bar 类。编译器无法弄清楚 foo::bar 是什么,除非它为所有可能的 T 实例化 foo。标准说它不必这样做。

您与好友操作员的原始解决方案有什么问题?您不必内联定义它,只需在本地类中声明它即可。