重载operator <<(模板化)时如何修复"模糊过载"错误?

Joe*_*oey 3 c++ templates overloading compiler-errors operator-keyword

我试图重载<<运算符,但我得到以下错误:

错误:'std :: cout <<"Test"'中'operator <<'的模糊重载

..跟随50亿其他类似的错误:

c:\ mingw\bin ../ lib/gcc/mingw32/4.5.2/include/c ++/ostream:165:7:注意:候选人是:...

这是因为我在main.cpp文件中使用cout.

这是我的代码:

在BinTree.h中:

    template <typename T>
    class BinTree{
    ...
    friend std::ostream& operator<< <>(std::ostream&, const T&);
Run Code Online (Sandbox Code Playgroud)

在BinTree.cpp中:

    template <typename T>
    std::ostream& operator<< (std:: ostream& o, const T& value){
        return o << value;
    }
Run Code Online (Sandbox Code Playgroud)

在此先感谢您提供任何帮助.

Dav*_*rle 6

您的函数具有与已定义的签名相同的签名.这就是为什么编译器会抱怨模糊的过载.您的函数尝试定义一个函数以将所有内容流式传输到ostream.此功能已存在于标准库中.

template <typename T>
std::ostream& operator<< (std:: ostream& o, const T& value){
    return o << value;
}
Run Code Online (Sandbox Code Playgroud)

您可能想要做的是编写一个函数来定义BinTree如何流式传输(到所有内容).请注意,流类型是模板化的.因此,如果将调用链接到流运算符,则会传输具体类型.

template <typename T, typename U>
T& operator<< (T& o, const BinTree<U>& value){
    //Stream all the nodes in your tree....
    return o;
}
Run Code Online (Sandbox Code Playgroud)