错误:无法将std :: ostream左值绑定到std :: basic_ostream <char>&amp;&amp; </char>

时间:2013-12-30 20:47:14

标签: c++

之前已在Overloading operator<<: cannot bind lvalue to ‘std::basic_ostream<char>&&’中询问过,以下代码会产生:

error: cannot bind ‘std::ostream {aka std::basic_ostream<char>}’ lvalue to ‘std::basic_ostream<char>&&’

代码:

// tried forward declaring but this did not help
namespace Tree {
    template<typename> class Node;
};
template<typename T> std::ostream& operator<<(std::ostream&, const Tree::Node<T>&);

namespace Tree {
    template<typename> class Tree;

    template<typename T>
    class Node {
        friend inline std::ostream& operator<<(std::ostream& out, const Node& node) {
            return out << node.getData();
        }
        friend class Tree<T>;
        // member declarations
        ...
    };

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

        std::ostream& showInOrder(std::ostream& out, std::unique_ptr<Node<T>> const &node) const {
            if(node->left) showInOrder(out, node->left);
            out << node << " "; // error: cannot bind 'std:ostream {...} to lvalue'
            if(node->right) showInOrder(out, node->right);
            return out;
        }
    };
};

根据Bo Persson在上述链接中的回答,我对"non-deducible context"有疑问,但是接受的答案并没有解决问题。

1 个答案:

答案 0 :(得分:5)

nodestd::unique_ptr<Node<T>>。你需要取消引用它:

out << *node << " ";