This question is related to Type erasing type erasure, `any` questions?
Given the class wstr below (just a string wrapper)
class wstr { public: std::string text; }; I have an any...
std::any myAny({myWstr}); ..and I want to cast (convert) it to a string..
std::string myString = std::any_cast<std::string>(myAny); ... Is there a means of doing this by using template specialization, or (as I suspect) is this missing the point of using std::any?
This question is not about implicit conversion. I was thinking that I may need to write a friend function/overloading the cast, similar to writing ostream operator extensions.
Another way of asking this would be: Am I correct in thinking an std::any_cast does NOT CAST to anything, but rather ONLY CASTS a std::any back to it's original form, and therefore one cannot overload a function that supports the cast to eg, std::string, and is not available (for some reason) for friend function overloading / template specialization?
wstr myWstr("foo"); std::any myAny({myWstr}); wstr myWstr = std::any_cast<wstr>(myAny); //is okay. std::string mMytr = std::any_cast<std::string>(myAny); //No overloads!
std::any<wstr>is wrong, becausestd::anyisn't a template. Are you perhaps thinking aboutstd::variantorstd::optional?any_castis not really to cast between different types but merely to access the value stored in theanyin a typesafe mannerany_cast. If that's what you want to do, then you are probably usinganyoutside of its intended use case and purpose.