【问题标题】:invisible operator<< overload for inner class内部类的隐形运算符<<重载
【发布时间】:2014-08-07 02:43:32
【问题描述】:

为什么 main 中的 operator

#include <iostream>

struct Base {};

std::ostream& operator<<(std::ostream& os, const Base&) { return os << "Hi\n"; }

template <class T>
struct Container
{
   class Derived : Base {
       template <class U>
       friend std::ostream& operator<<(std::ostream& os, const typename Container<U>::Derived&);
   };
};

template <class U>
std::ostream&
operator<<(std::ostream& os, const typename Container<U>::Derived& der)
{
   return os << static_cast<const Base&>(der);
}

int main()
{
   Container<int>::Derived d;
   std::cout << d;
   return 0;
}

g++ 说:

/tmp $ g++ test.c
test.c: In function ‘int main()’:
test.c:28: error: ‘Base’ is an inaccessible base of ‘Container<int>::Derived’
/tmp $ 

编辑:私有继承是有意的。这就是为什么 operator

EDIT2:好友声明的固定位置;在内部类中。

【问题讨论】:

  • 要做: public Base
  • operator&lt;&lt; 是Container 的朋友,而不是Derived 的朋友。
  • 哎呀,错字了;从防火墙后面手动复制

标签: c++


【解决方案1】:

在你的:

template <class U>
std::ostream&
operator<<(std::ostream& os, const typename Container<U>::Derived& der)

第二个参数中的U 处于非推导上下文中(参见 §14.8.2.5/5),因此编译器在 在operator&lt;&lt; 上进行运算符重载解析 main。结果,这个函数没有实例化 在重载集和重载决议(总是 忽略访问问题)选择非模板operator&lt;&lt; 服用Base const&amp;。访问控制然后导致错误 你看到了。

有几种解决方案。可能最简单的就是不 将operator&lt;&lt; 的Derived 声明为模板,但要 在Derived 中将其实现为内联朋友内联:

friend std::ostream& operator<<( std::ostream& dest, Derived const& obj )
{
    return os << static_cast<Base const&>( obj );
}

这是如何工作的有点棘手。你要声明的朋友 不是模板;有一个单独的非模板函数 对于Container 的每个实例化。如果不是内联, 你必须提供一个单独的、非模板化的实现 对于每种类型。但由于它是内联的,编译器提供了它 为你。虽然没有注入函数的名称 在周围环境中,会被ADL发现。

当然,因为这个operator&lt;&lt; 不是模板,所以有 找到它时不涉及任何论据推导。

【讨论】:

    猜你喜欢
    • 2017-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多