Is it possible to declare a boost::type_erasure::any in a way that constructing and assigning from string literal or char const* automatically copies the string into a std::string and stores that in the boost::type_erasure::any object?
By default, a boost::type_erasure::any just stores the string pointer.
The aim is to avoid a source of errors when users of my any type assign a string pointer to it, assuming a copy will be made (like std::string does) and then the lifetime of the string ends before my any is read, causing a crash.
Example:
#include <boost/type_erasure/operators.hpp>
#include <boost/type_erasure/any.hpp>
#include <boost/type_erasure/any_cast.hpp>
#include <boost/type_erasure/relaxed.hpp>
#include <boost/mpl/vector.hpp>
#include <iostream>
namespace te = boost::type_erasure;
using my_any = te::any< boost::mpl::vector<
te::copy_constructible<>,
te::destructible<>,
te::typeid_<>,
te::relaxed
/* I believe some changes here would do the trick */
>>;
using namespace std;
int main()
{
// Store an std::string by explicitly calling string constructor.
my_any a = string("abc");
// The following should copy-construct an std::string too but it just stores
// the string pointer.
my_any b = "abc";
// Works as expected.
cout << te::any_cast<string>( a ) << endl;
// This crashes because the underlying type of b is not std::string.
// With some changes to the my_any type this shouldn't crash anymore.
cout << te::any_cast<string>( b ) << endl;
}
No,
anystores anything.const char*is anything.Note that
"hello"sis a literal of typestd::string.