[英]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";
當我嘗試運行此代碼時,出現以下錯誤:
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";
將按預期方式打印“算盤”。
作為一個字符串,它應該有一個size()方法
它不是string
,而是一個variant
。 首先,您需要告訴編譯器您知道里面有一個string
–即使用boost::get<std::string>(vec[0])
檢索它。
請務必閱讀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.