I have a boost variant of looking like this: typedef boost::variant<int, float, double, long, bool, std::string, boost::posix_time::ptime> variant;
I have a need for being able to convert any of the values in this variant to a std::string, I wondered if there is some template type function I could use to do this?
Or what would be the most effective way?
I would currently implement a bunch of overloaded functions, each taking a type and then doing the conversion using std::stringstream
or for posix_time
i'd use it's conversion function. Perhaps there is a better way?
Boost. Variant, part of collection of the Boost C++ Libraries. It is a safe, generic, stack-based discriminated union container, offering a simple solution for manipulating an object from a heterogeneous set of types in a uniform manner.
In boost::variant , it computes the maximum sized object, and uses "placement new" to allocate the object within this buffer. It also stores the type or the type index. Note that if you have Boost installed, you should be able to see the source files in "any. hpp" and "variant.
boost::apply_visitor — Allows compile-time checked type-safe application of the given visitor to the content of the given variant, ensuring that all types are handled by the visitor.
There is no functionality difference between string and std::string because they're the same type.
Use boost::lexical_cast, which hides the whole stringstream
thing behind a convenient wrapper. This also works with boost::posix_time, since it has a suitable operator<<
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With