我已经读到,如果boost::variant
的所有变体都可以流式传输,则可以流式传输。然而,
#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
}
无法编译。为什么?
版本:
提升1.53
GCC 4.6.3
最佳答案
我还没有检查序列化的文档,但是我很确定operator<<
类型的boost::variant
必须通过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';
}
输出:
3
1 1 1
3