我正在尝试使用Boost.Assign填充boost::property_tree::ptree
。所以,我得到了以下工作:
namespace bpt = boost::property_tree;
bpt::ptree pt;
boost::assign::make_list_inserter
(boost::bind(&bpt::ptree::put<std::string>, pt, _1, _2))
("one.two.three", "four")
("one.two.five", "six");
然而,当我试图让这段代码更好看时,它无法编译:
typedef bpt::ptree& (bpt::ptree::*PutType)
(const bpt::path_of<std::string>::type&, const std::string &);
PutType Put = &bpt::ptree::put<std::string>;
inline boost::assign::list_inserter<PutType> put(bpt::ptree &pt) {
PutType putFunction = boost::bind(Put, pt, _1, _2); // !!! compile error
return boost::assign::make_list_inserter(putFunction);
}
//and use it like:
put(pt)
("one.two.three", "four")
("one.two.five", "six");
错误讯息是
SomeFile.cpp:在函数'boost :: assign :: list_inserter&lt; boost :: property_tree :: ptree&amp; (boost :: property_tree :: ptree :: *)(const boost :: property_tree :: string_path&lt; std :: string,boost :: property_tree :: id_translator&lt; std :: string&gt;&gt;&amp;,const std :: string&amp;),boost :: assign_detail :: forward_n_arguments&gt;放(升压:: property_tree :: ptree中&安培;)”:
SomeFile.cpp:42:错误:无法转换'boost :: _ bi :: bind_t&lt; boost :: property_tree :: ptree&amp;,boost :: _ mfi :: mf2&lt; boost :: property_tree :: ptree&amp;,boost: :property_tree :: ptree,const boost :: property_tree :: string_path&lt; std :: string,boost :: property_tree :: id_translator&lt; std :: string&gt; &gt;&amp;,const std :: string&amp;&gt ;, boost :: _ bi :: list3&lt; boost :: _ bi :: value&lt; boost :: property_tree :: ptree&gt ;, boost :: arg&lt; 1&gt ;, boost: :ARG&LT 2 - ; &GT; &gt;'到'boost :: property_tree :: ptree&amp; (boost :: property_tree :: ptree :: *)(const boost :: property_tree :: string_path&lt; std :: string,boost :: property_tree :: id_translator&lt; std :: string&gt;&gt;&amp;,const std ::初始化
中的字符串&amp;)
使代码工作的最佳方法是什么?
答案 0 :(得分:3)
代码中有几处错误:
boost::bind()
按值存储绑定参数,以便boost::bind(&bpt::ptree::put<std::string>, pt, _1, _2)
复制pt
并填充该副本。改为使用指针:boost::bind(&bpt::ptree::put<std::string>, &pt, _1, _2)
或使用boost::ref(pt)
。boost::bind
返回的对象无法转换为指针类型,这就是PutType putFunction = boost::bind(Put, pt, _1, _2);
无法编译的原因。在没有auto
关键字的C ++ 03中,您无法轻松捕获boost::bind
和boost::list_inserter
的类型。您可以将两者的结果都包装到boost::function<>
中,但在我看来,这样做太过苛刻了。
但是您可以使用plain:
在C ++ 03中实现所需的语法namespace bpt = boost::property_tree;
struct PtreeInserter
{
bpt::ptree* pt;
PtreeInserter(bpt::ptree& pt) : pt(&pt) {}
template<class A1, class A2>
PtreeInserter const& operator()(A1 a1, A2 a2) const {
pt->put(a1, a2);
return *this;
}
};
int main() {
bpt::ptree pt;
typedef PtreeInserter put;
put(pt)
("one.two.three", "four")
("one.two.five", "six");
}