c++ - 通用容器的输出流

标签 c++ templates ostream

我创建了这个模板函数:

// Output stream for container of type C
template<class C>
ostream& operator<<(ostream& os, const C& c) {
    os << "[";
    for (auto& i : c) {
        os << i;
        if (&i != &c.back()) os << ", ";
    }
    os << "]" << endl;
    return os;
}

但是我有这个错误:

error: use of overloaded operator '<<' is ambiguous (with operand types 'std::ostream' (aka 'basic_ostream') and 'const char [2]')

错误出现在函数体的第一行。

最佳答案

本声明

template<class C>
ostream& operator<<(ostream& os, const C& c)

匹配任何类型。特别是,当您在该运算符内部调用时

os << "[";
os << i;
os << "]" << endl;

对于所有这些调用,除了现有的字符串和 endl 输出运算符之外,您的运算符也是匹配的。

不要为您不拥有的类型提供运算符。相反,你可以写一个

void print(const my_container&);

或使用标签来解决歧义。例如,您可以使用

template <typename T>
struct pretty_printed_container {
    const T& container;
};

template <typename T>
pretty_printed_container<T> pretty_print(const T& t) { return {t};}

相应地修改您的输出运算符

template<class T>
std::ostream& operator<<(std::ostream& os, const pretty_printed_container<T>& c) {
    os << "[";
    for (const auto& i : c.container) {
        os << i;
        if (&i != &c.container.back()) os << ", ";
    }
    os << "]" << std::endl;
    return os;
}

然后像这样使用它

int main() {
    std::vector<int> x{1,2,3,4,5};
    std::cout << pretty_print(x);
}

输出:

[1, 2, 3, 4, 5]

关于c++ - 通用容器的输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59214136/

相关文章:

c++ - gprof 报告没有累积时间

java - FIX 通信模型 - 消息或套接字

c++ - 安全的多线程计数器增量

c++ - C++ 中的模板 "Adapters"

c++ - "Cannot convert ' MyClass ' to ' bool '"模板编程错误

c++ - 获取 C++ 输出流中元素的大小

c++ - 当我引用 std::ostream 进行编译时,会弹出一个奇怪的错误

c++ - 在 C++11 中左值需要作为一元 '&' 操作数

c++ - 避免枚举作为接口(interface)标识符 C++ OOP

c++ - 模板基类类型定义和函数的更好 C++ 语法?