boost::variant and printing methods of elements in vector

1.1k views Asked by At
 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. 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.

2

There are 2 answers

0
Konrad Rudolph On BEST ANSWER

being a string it should have a size() method

It’s not a string – it’s a variant. You first need to tell the compiler that you know there’s a string inside – i.e. retrieve it using boost::get<std::string>(vec[0]).

Be sure to read the Boost.Variant tutorial.

0
Nim On

You need to get the first type of this variant (which is the string), the class boost::variant which you are accessing with vector::at() has no method called size(), try something like::

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