c++ - operator<<(ostream&, const BigUnsigned<I>&) 必须只有一个参数

标签 c++ templates c++11 operator-overloading

我试图将模板化类的模板化成员函数的声明和定义分开,但最终出现以下错误和警告。

template <typename I>
class BigUnsigned{
    const size_t cell_size=sizeof(I);
    std::vector<I> _integers;
public:
    BigUnsigned();
    BigUnsigned(I);
    friend std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu);
};

std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu){
    for (auto integer : bu._integers){
        out<<integer<<std::endl;
    }
    return out;
}

../hw06/bigunsigned.h:13:77: warning: friend declaration 'std::ostream& operator<<(std::ostream&, const BigUnsigned&)' declares a non-template function [-Wnon-template-friend] friend std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu); ^ ../hw06/bigunsigned.h:13:77: note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here) ../hw06/bigunsigned.h:16:51: error: invalid use of template-name 'BigUnsigned' without an argument list std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu){ ^ ../hw06/bigunsigned.h: In function 'std::ostream& operator<<(std::ostream&, const int&)': ../hw06/bigunsigned.h:17:28: error: request for member '_integers' in 'bu', which is of non-class type 'const int' for (auto integer : bu._integers){ ^

当我像这样加入声明和定义时,一切都可以正常编译。

template <typename I>
class BigUnsigned{
    const size_t cell_size=sizeof(I);
    std::vector<I> _integers;
public:
    BigUnsigned();
    BigUnsigned(I);
    friend std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu){
        for (auto integer : bu._integers){
            out<<integer<<std::endl;
        }
        return out;
    }
};

目的是打印成员变量_integers到cout。可能是什么问题?

附言:使用 this question我免费提供了该功能,但没有帮助。

最佳答案

BigUnsigned是模板类型所以

std::ostream& operator<<(std::ostream& out, const BigUnsigned& bu)

将无法工作,因为没有 BigUnsigned .您需要将 friend 函数设为模板,以便您可以采用不同类型的 BigUnsigned<some_type>

template <typename I>
class BigUnsigned{
    const size_t cell_size=sizeof(I);
    std::vector<I> _integers;
public:
    BigUnsigned();
    BigUnsigned(I);
    template<typename T>
    friend std::ostream& operator<<(std::ostream& out, const BigUnsigned<T>& bu);
};

template<typename T>
std::ostream& operator<<(std::ostream& out, const BigUnsigned<T>& bu){
    for (auto integer : bu._integers){
        out<<integer<<std::endl;
    }
    return out;
}

第二个示例之所以有效,是因为它是在类内部声明的,所以它使用了该类使用的模板类型。

关于c++ - operator<<(ostream&, const BigUnsigned<I>&) 必须只有一个参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34928076/

相关文章:

c++ - 将 header 中声明的 QTextStream 设置为标准输出

c++ - 程序在 FTP 后不工作

c++ - std::set 用作静态模板化成员变量

c++ - 在 C++ 中使用枚举作为模板类型参数

c++ - Clang 的 libc++:在 std::chrono::duration 的定义中使用 long long

c++ - 从 C++ 调用 Lua 函数

c++ - 分析永不退出的基于 C 或 C++ 的应用程序

c++ - 一次清除所有 Cmake 变量

C++ std::enable_if 区分 float 和有符号数?

C++ 字符串 - 使用初始化列表构造函数时的奇怪行为