简体   繁体   English

为什么boost :: variant缺少运算符<<?

[英]Why is this boost::variant missing operator<<?

I've read that a boost::variant is streamable if all of its variants are streamable. 我读过,如果boost::variant所有变体都是可流式的,则它是可流式的。 However, 然而,

#include <iostream>
#include <vector>
#include <string>
#include <boost/variant.hpp>

std::ostream& operator<<(std::ostream& out, const std::vector<int>& v) {
    for(int i = 0; i < v.size(); ++i)
        out << " " << v[i];
    return out;
}

int main() {
    boost::variant<int, std::string > a(3);
    std::cout << a << '\n'; // OK

    std::vector<int> b(3, 1);
    std::cout << b << '\n'; // OK

    boost::variant<int, std::vector<int> > c(3);
    std::cout << c << '\n'; // ERROR
}

fails to compile. 无法编译。 Why? 为什么?

Versions: 版本:

  • Boost 1.53 提升1.53
  • GCC 4.6.3 GCC 4.6.3

I haven't checked the documentation of serialization, but I'm pretty sure that operator<< for the types of boost::variant needs to be either found by Argument Dependent Lookup or else be present in boost namespace. 我还没有检查序列化的文档,但是我很确定, boost::variant类型的operator<<必须由Argument Dependent Lookup查找,或者存在于boost命名空间中。

This works : 这有效

#include <iostream>
#include <vector>
#include <string>
#include <boost/serialization/variant.hpp>

namespace boost {

    std::ostream& operator<<(std::ostream& out, const std::vector<int>& v) {
        for(int i = 0; i < v.size(); ++i)
            out << " " << v[i];
        return out;
    }

}

int main() {
    boost::variant<int, std::string > a(3);
    std::cout << a << '\n';

    {
    using namespace boost;
    std::vector<int> b(3, 1);
    std::cout << b << '\n';
    }

    boost::variant<int, std::vector<int> > c(3);
    std::cout << c << '\n';
}

Output: 输出:

3
 1 1 1
3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM