Since I discovered boost::lexical_cast
all conversions are a breeze. That's until trying to convert a tuples elements into a string. Like Int2String
or Double2String
I want a way to generate a single string from a tuple of arbitrary number of elements
Since the subject of conversion has arbitrary (yet compile time known) dimension, after some research I've looked into boost::fusion
and found this solution :
#include <string>
#include <boost/lexical_cast.hpp>
#include <boost/noncopyable.hpp>
#include <boost/fusion/include/for_each.hpp>
template <class Sequence>
std::string StringFromSequence(const Sequence &seq)
{
std::string result;
boost::fusion::for_each(seq, toString(result));
return result;
}
Where toString
is a functor applying the lexical cast to the objects that's been called for :
struct toString: boost::noncopyable
{
explicit toString(std::string& res) : result(res)
{
}
template <class T>
void operator()(const T& v)
{
result += boost::lexical_cast<std::string>(v);
}
private:
std::string &result;
};
When trying to use that though
std::tuple<int, char, double> tup{ 1, 'a', 2.2 };
toString(tup);
I get a compilation error
error C2893: Failed to specialize function template 'enable_if, void>::type boost::fusion::for_each(const Sequence &,const F &)'
- Can someone spot and correct the error ?
- Are there any (maybe boost free) alternatives ? (it would take compile time recursion and I was hopefully trying to avoid all that boilerplate code)