Boost :: variant <T> to std :: string
I have a boost option that looks like this: typedef boost::variant<int, float, double, long, bool, std::string, boost::posix_time::ptime> variant;
I need to convert any of the values ββin this option to std :: string, I was wondering if there is some kind of template type function that I could use for this?
Or what would be the most efficient way?
I am currently implementing a bunch of overloaded functions, each of which takes a type, and then performs the conversion using std::stringstream
or for posix_time
, I would use its conversion function. Perhaps there is a better way?
Use boost :: lexical_cast , which hides the entire stringstream
thing behind a convenient shell. This also works with boost :: posix_time, as it has a suitable operator<<
.
Try the following:
struct to_string_visitor : boost::static_visitor<> { std::string str; template <typename T> void operator()(T const& item) { str = boost::lexical_cast<std::string>(item); } void operator()(boost::posix_time::ptime const & item) { //special handling just for ptime } }; int main(){ variant v = 34; to_string_visitor vis; boost::apply_visitor(vis, v); cout << vis.str << endl; }
See general convert from boost :: variant <T> for input . You must be able to adapt this answer to your situation. You can use boost::lexical_cast
for all of your types except boost::posix_time::ptime
, where you will probably need a special solution. All this in static_visitor
using operator overloading (template + one for ptime).
a cleaner and more elegant (but no more efficient) way to convert a particular type to std::string
is to use
template<typename Target, typename Source> Target lexical_cast(const Source& arg);
from
#include <boost/lexical_cast.hpp>
The type to be converted must provide the usual "<lt;" statement for ostream.
usage example: std::string s = boost::lexical_cast<std::string>( 17 ); assert( s == "17" );
std::string s = boost::lexical_cast<std::string>( 17 ); assert( s == "17" );