首页 > 解决方案 > 通用容器的输出流

问题描述

我创建了这个模板函数:

// 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;
}

但我有这个错误:

错误:重载运算符“<<”的使用不明确(操作数类型为“std::ostream”(又名“basic_ostream”)和“const char [2]”)

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

标签: c++templatesostream

解决方案


本声明

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]

推荐阅读