c++ - vector中元素的boost::variant和打印方法

标签 c++ boost-variant

 std::vector< boost::variant<std::string, int> > vec;
 std::string s1("abacus");
 int i1 = 42;
 vec.push_back(s1);
 vec.push_back(i1);
 std::cout << vec.at(0).size() << "\n";

当我尝试运行此代码时,出现以下错误:

main.cpp:68: error: ‘class boost::variant<std::basic_string<char, std::char_traits<char>, std::allocator<char> >, int, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_, boost::detail::variant::void_>’ has no member named ‘size’
make: *** [main.o] Error 1

然而,作为一个字符串,它应该有一个 size() 方法。我不确定出了什么问题。请注意,将最后一行替换为:

std::cout << vec.at(0) << "\n";

将按预期打印“abacus”。

最佳答案

being a string it should have a size() method

这不是 string – 这是一个variant .你首先需要告诉编译器你知道有一个string内部 - 即使用 boost::get<std::string>(vec[0]) 检索它.

请务必阅读 Boost.Variant tutorial .

关于c++ - vector中元素的boost::variant和打印方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5180034/

相关文章:

c++ - Arduino 从 'char' 到 'char*' 的无效转换

c++ - 当 std::vector 增长时,其中元素的地址是否不再有效?

c++ - c++11 中的 boost::variant 和多态性

java - 如何将 Boost::make_recursive_variant 对象转换为字符串?

c++ - 为什么 Boost Variant 使用模板构造函数而不是 boost::beast::websocket::stream 的移动构造函数?

c++ - 是否可以在 GA144 上运行仿真的 C 代码?

c++ - 如何使用 std::multimap 将整数键映射到用作多维数组坐标的两个整数值(对于 Tic Tac Toe)?

c++ - 支持 CSS3 的 C/C++ CSS 解析器?

c++ - 增加访问量可能存在错误

c++ - boost::spirit::karma:将 no_delimit 与替代项一起使用