我觉得我有一个严肃的'Doh!' 这一刻......
我目前正在尝试实施:
std::ostream& operator<<(std::ostream &out, const MyType &type)
Run Code Online (Sandbox Code Playgroud)
MyType持有int :: char和bool的boost ::变体.IE:让我的变体流畅.
我试过这样做:
out << boost::apply_visitor(MyTypePrintVisitor(), type);
return out;
Run Code Online (Sandbox Code Playgroud)
MyTypePrintVisitor有一个模板化函数,它使用boost :: lexical_cast将int,char或bool转换为字符串.
但是,这不会编译,因为apply_visitor不是MyType的函数.
然后我这样做了:
if(type.variant.type() == int)
out << boost::get<int> (type.variant);
// So on for char and bool
...
Run Code Online (Sandbox Code Playgroud)
我缺少一个更优雅的解决方案吗?谢谢.
编辑:问题解决了.请参阅第一个解决方案和我对此的评论.
variant如果所有包含的类型都是可流式的,您应该能够流式传输.示范:
#include <boost/variant.hpp>
#include <iostream>
#include <iomanip>
struct MyType
{
boost::variant<int, char, bool> v;
};
std::ostream& operator<<(std::ostream &out, const MyType &type)
{
out << type.v;
}
int main()
{
MyType t;
t.v = 42;
std::cout << "int: " << t << std::endl;
t.v = 'X';
std::cout << "char: " << t << std::endl;
t.v = true;
std::cout << std::boolalpha << "bool: " << t << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
输出:
int: 42
char: X
bool: true
Run Code Online (Sandbox Code Playgroud)
如果您确实需要使用访问者(可能是因为某些包含的类型不可流化),那么您需要将其应用于variant自身; 您的代码片段看起来就像是将它应用于MyType对象.