c – 如何打印strearchble类型的boost :: variant?
发布时间:2020-12-16 05:01:16 所属栏目:百科 来源:网络整理
导读:我觉得我有一个严肃的’Doh
我觉得我有一个严肃的’Doh!’这一刻……
我目前正在尝试实施: std::ostream& operator<<(std::ostream &out,const MyType &type) MyType持有int :: char和bool的boost ::变体. IE:让我的变体流畅. 我试过这样做: out << boost::apply_visitor(MyTypePrintVisitor(),type); return out; 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 ... 我缺少一个更优雅的解决方案吗? 编辑:问题解决了.请参阅第一个解决方案和我对此的评论. 解决方法
如果变量的所有包含类型都是可流式的,您应该能够流式传输变量.示范:
#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; } 输出: int: 42 char: X bool: true 如果您确实需要使用访问者(可能是因为某些包含的类型不可流化),那么您需要将其应用于变体本身;您的代码片段看起来就像是将它应用于MyType对象. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |