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?

+8
c ++ string variant
source share
4 answers

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

+9
source share

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; } 
+3
source share

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

+1
source share

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" );

0
source share

Source: https://habr.com/ru/post/649946/


All Articles