-
正如较旧的答案also指出您必须满足以下要求boost::property_tree::detail::is_translator
,所以你需要internal_type
/ external_type
类型定义。
typedef T internal_type;
typedef T external_type;
-
接下来,循环错误,需要检查值提取的结果:
while (ss >> temp_value)
values.push_back(temp_value);
将您自己的类型放入 boost 命名空间中是不好的做法。只有专业化translator_between<>
需要在那里。
您可以简化和概括很多代码
全部在一个工作演示中:
Live On Coliru http://coliru.stacked-crooked.com/a/2d31028ff991d28b
#include <boost/optional.hpp>
#include <boost/property_tree/ptree.hpp>
#include <vector>
#include <list>
namespace mylib { namespace xml_translators {
template<typename T> struct container
{
// types
typedef T internal_type;
typedef T external_type;
boost::optional<T> get_value(const std::string& str) const
{
if (str.empty())
return boost::none;
T values;
std::stringstream ss(str);
typename T::value_type temp_value;
while (ss >> temp_value)
values.insert(values.end(), temp_value);
return boost::make_optional(values);
}
boost::optional<std::string> put_value(const T& b) {
std::stringstream ss;
size_t i = 0;
for (auto v : b)
ss << (i++?" ":"") << v;
return ss.str();
}
};
} }
namespace boost { namespace property_tree {
template<typename ch, typename traits, typename alloc, typename T>
struct translator_between<std::basic_string<ch, traits, alloc>, std::vector<T> > {
typedef mylib::xml_translators::container<std::vector<T> > type;
};
template<typename ch, typename traits, typename alloc, typename T>
struct translator_between<std::basic_string<ch, traits, alloc>, std::list<T> > {
typedef mylib::xml_translators::container<std::list<T> > type;
};
} }
#include <sstream>
#include <iostream>
#include <boost/property_tree/xml_parser.hpp>
int main()
{
std::stringstream ss;
using boost::property_tree::ptree;
{
ptree pt;
pt.add("base", std::vector<double> { 1, 6, 3 });
write_xml(ss, pt, boost::property_tree::xml_writer_settings<std::string>(' ', 2));
}
{
ptree pt;
read_xml(ss, pt);
std::cout << "As string: '" << pt.get("base", "") << "'\n";
auto roundtrip = pt.get<std::list<int> >("base");
for (auto i : roundtrip)
std::cout << i << std::endl;
}
}
Prints
As string: '1 6 3'
1
6
3
¹ Boost property_tree:每个键有多个值 https://stackoverflow.com/questions/13072704/boost-property-tree-multiple-values-per-key,另请参阅恒等转换器http://www.boost.org/doc/libs/1_64_0/doc/html/boost/property_tree/id_translator.html http://www.boost.org/doc/libs/1_64_0/doc/html/boost/property_tree/id_translator.html