How to raise :: any_cast in std :: string

I have this test fragment

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

}

This boost::any_castis a bad_casting exception for std::string. This means that for some reason he is not able to give boost::anyin std::string. While other classes, such as bitsetor my own custom class, work. Could you tell me why there is a way out of this?

+4
source share
2 answers

"Mayukh"is not std::string, it is an array constof 7 characters {'M', 'a', 'y', 'u', 'k', 'h', '\0'}. In C ++ 14 "Mayukh"sis std::stringafter using namespace std::literals::string_literals;.

In C ++ 11 is std::string("Mayukh")also std::string.

boost::any (, decay/const/etc). . . :

, , , .. 5, int "5", 5.0. , , , - .

any . , -, , , ( short s: int64_t uint64_t, "hello" std::string("hello") ..) .

+11

, "Mayukh" std::string. a const char[7], const char*:

boost::any a = "Mayukh";
std::cout << a.type().name() << '\n';  // prints PKc, pointer to const char
if (boost::any_cast<const char*>(&a)) {
    std::cout << "yay\n";              // prints yay
}

any_cast<std::string>, std::string:

container.push_back(std::string("Mayukh"));
+4

All Articles