自从我发现了
由于转换对象具有任意(但在编译时已知)维度,经过了一些研究后,我查阅了
尝试使用时:
boost::lexical_cast
后,所有的类型转换都变得轻而易举。但当我尝试将元组元素转换为字符串时,情况就不同了。与 Int2String
或 Double2String
类似,我想要一种从任意数量元素的元组生成单个字符串的方法。由于转换对象具有任意(但在编译时已知)维度,经过了一些研究后,我查阅了
boost::fusion
并找到了这个解决方案:#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;
}
其中toString
是一个函数对象,将被调用的对象应用于词法转换:
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;
};
尝试使用时:
std::tuple<int, char, double> tup{ 1, 'a', 2.2 };
toString(tup);
我遇到了编译错误。
错误 C2893: 无法特化函数模板 'enable_if, void>::type boost::fusion::for_each(const Sequence &,const F &)'
- 有人能找出并纠正这个错误吗?
- 是否有任何(可能是不使用boost的)替代方案?(这将需要编译时递归,而我希望尽可能避免所有那些样板代码)
std::string
时,我会得到这个错误:error: no matching function for call to ‘to_string(const std::__cxx11::basic_string<char>&)’ s += to_string(std::forward<H>(h));
有什么想法如何解决它吗? - ph_0