Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

boost::variant<T> to std::string

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?

like image 782
Tony The Lion Avatar asked Dec 08 '10 15:12

Tony The Lion


People also ask

What is boost :: variant?

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.

How boost variant works?

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.

What is boost:: apply_ visitor?

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.

Is string the same as std :: string?

There is no functionality difference between string and std::string because they're the same type.


1 Answers

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<<.

like image 65
Marcelo Cantos Avatar answered Nov 03 '22 08:11

Marcelo Cantos