c++ - 重载运算符<< : cannot bind lvalue to ‘std::basic_ostream<char>&&’

标签 c++

我有一个使用嵌套类的类,并且想使用嵌套类 operator<<定义 operator<<在上层类(Class)。这是我的代码的样子:

#include <memory>
#include <iostream>

template<typename T>
struct classA {
  struct classB
  {
    template<typename U>
    friend inline std::ostream& operator<< (std::ostream &out,
                                            const typename classA<U>::classB &b);
  };

  classB root;

  template<typename U>
  friend std::ostream& operator<< (std::ostream &out,
                                   const classA<U> &tree);
};

template<typename T>
inline std::ostream& operator<< (std::ostream &out,
                                 const classA<T> &tree)
{
  out << tree.root;
  return out;
}

template<typename T>
inline std::ostream& operator<< (std::ostream &out,
                                 const typename classA<T>::classB &b)
{
  return out;
}

int main()
{
  classA<int> a;
  std::cout << a;
}
  • 在不支持C++11的情况下编译时,编译器似乎找不到内部类的operator<<定义:

    so.hpp:24:7: error: no match for ‘operator<<’ in ‘out << tree.classA<int>::root’
    so.hpp:24:7: note: candidates are: ...
    
  • 使用 std=c++0x 编译时使用 GCC 4.6 和 4.7:

    so.hpp:21:3: error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’
    In file included from /usr/include/c++/4.7/iostream:40:0,
                     from so.hpp:2:
    /usr/include/c++/4.7/ostream:600:5: error:   initializing argument 1 of ‘std::basic_ostream<_CharT, _Traits>& std::operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&) [with _CharT = char; _Traits = std::char_traits<char>; _Tp = classA<int>::classB]’
    

谁能告诉我为什么这段代码不合法​​,什么是做我想做的最好的方法?

最佳答案

您的 "non-deducible context" 有问题在这个运算符中

template<typename T>
inline std::ostream& operator<< (std::ostream &out,
                                 const typename classA<T>::classB &b)
{
  return out;
}

编译器无法判断 T 的值是什么将导致 classB与您要传递的参数相匹配。所以这个模板不考虑!

在 C++11 模式下,编译器会继续从标准库中查找匹配项

operator<<(std::basic_ostream<_CharT, _Traits>&&, const _Tp&)

它在哪里可以匹配_Tp几乎任何类型,包括classA<T>::classB ,但注意第一个参数不匹配。

关于c++ - 重载运算符<< : cannot bind lvalue to ‘std::basic_ostream<char>&&’ ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10651161/

相关文章:

c++ - uint32_t,用于表示变量大小的 int_t 表示法

c++ - 将 .end() 与值进行比较

C++ 链接器错误

c++ - 我需要 C++ 中的模数

C++0x printf() 为 double 打印错误的值

c++ - qt bindvalue() 无法动态绑定(bind)值

c++ - 试图理解 C++ 中的堆栈和堆

C++按键: getch, cin.get?

c++ - 有哪些好的 3D 插值库?

C++通过在基类构造函数中调用它来将此指针添加到容器