简体   繁体   English

向量中元素的boost :: variant和打印方法

[英]boost::variant and printing methods of elements in vector

 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";

when I try to run this code, I get the following error: 当我尝试运行此代码时,出现以下错误:

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

however, being a string it should have a size() method. 但是,作为字符串,它应该具有size()方法。 I'm not sure what is going wrong. 我不确定发生了什么问题。 note that replacing the last line with: 请注意,将最后一行替换为:

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

will print "abacus", as expected. 将按预期方式打印“算盘”。

being a string it should have a size() method 作为一个字符串,它应该有一个size()方法

It's not a string – it's a variant . 它不是string ,而是一个variant You first need to tell the compiler that you know there's a string inside – ie retrieve it using boost::get<std::string>(vec[0]) . 首先,您需要告诉编译器您知道里面有一个string –即使用boost::get<std::string>(vec[0])检索它。

Be sure to read the Boost.Variant tutorial . 请务必阅读Boost.Variant教程

您需要获取此变体的第一种类型(即字符串),您要通过vector::at()访问的类boost::variant没有名为size()方法,请尝试以下方法:

boost::get<0>(vec.at(0)).size(); // I think that's the syntax....

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

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