How to boost::any_cast into std::string

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

In C++11, std::string("Mayukh") is a std::string as well.

boost::any only supports converting back to the exact same type (well, up to some decay/const/etc). It does not support conversions between the types. See boost any documentation:

Discriminated types that contain values of different types but do not attempt conversion between them, i.e. 5 is held strictly as an int and is not implicitly convertible either to "5" or to 5.0. Their indifference to interpretation but awareness of type effectively makes them safe, generic containers of single values, with no scope for surprises from ambiguous conversions.

Augmenting any with extra smart conversions can be done. For example, a pseudo-any that takes an incoming type, and possibly auto-converts it (so it won't store shorts: it converts all signed integral types to int64_t and unsigned to uint64_t, it converts "hello" to std::string("hello"), etc) before storing it.


That's because "Mayukh" is not a std::string. It's a const char[7], which would decay into 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
}

If you want to be able to use any_cast<std::string>, you'd need to put it in as a std::string:

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

This is not an answer to the question body but rather to the title to help others who also come here from google:

bool is_char_ptr(const boost::any & operand)
{
    try {
        boost::any_cast<char *>(operand);
        return true;
    }
    catch (const boost::bad_any_cast &) {
        return false;
    }
}

std::string any2string(boost::any anything)
{
    if (anything.type() == typeid(int)) {
        return std::to_string( boost::any_cast<int>(anything) );
    }
    if (anything.type() == typeid(double)) {
        return std::to_string(boost::any_cast<double>(anything));
    }
    if (is_char_ptr(anything)) {
        return std::string(boost::any_cast<char *>(anything));
    }
    if (boost::any_cast<std::string>(anything)) {
        return boost::any_cast<std::string>(anything);
    }

}

The last if looks weird but it works because the function is overloaded.

Tags:

C++

Boost

C++11