c++ - How to boost::any_cast into std::string -
i have test snippet
#include <boost/any.hpp> #include <iostream> #include <vector> #include <bitset> #include <string> class wrapper { int value; char character; std::string str; public: wrapper(int i, char c, std::string s) { value = i; character = c; str = s; } void get_data(){ std::cout << "value = " << value << std::endl; std::cout << "character = " << character << std::endl; std::cout << "string= " << str << std::endl; } }; int main(){ std::vector<boost::any> container; container.push_back(10); container.push_back(1.4); container.push_back("mayukh"); container.push_back('a'); container.push_back(std::bitset<16>(255) ); wrapper wrap(20, 'm', "alisha"); container.push_back(wrap); std::cout << boost::any_cast<int>(container[0]) << std::endl; std::cout << boost::any_cast<double>(container[1]) << std::endl; std::cout << boost::any_cast<std::string>(container[2]); std::cout << boost::any_cast<char>(container[3]) << std::endl; std::cout << boost::any_cast<std::bitset<16>>(container[4]); auto p = boost::any_cast<wrapper>(container[5]); p.get_data(); return 0; } in boost::any_cast gives bad_casting exception std::string. means reason not able typecast boost::any std::string. while other classes bitset or own user defined class working. can please tell me why & way out of this?
"mayukh" not std::string, const array of 7 characters {'m', 'a', 'y', 'u', 'k', 'h', '\0'}. in c++14, "mayukh"s std::string after using namespace std::literals::string_literals;.
in c++11, std::string("mayukh") std::string well.
boost::any supports converting exact same type (well, decay/const/etc). not support conversions between types. see boost documentation:
discriminated types contain values of different types not attempt conversion between them, i.e.
5held strictly int , not implicitly convertible either"5"or5.0. indifference interpretation awareness of type makes them safe, generic containers of single values, no scope surprises ambiguous conversions.
augmenting any smart conversions can done. example, pseudo-any takes incoming type, , possibly auto-converts (so won't store shorts: converts signed integral types int64_t , unsigned uint64_t, converts "hello" std::string("hello"), etc) before storing it.
Comments
Post a Comment