利用yaml-cpp库对数据结构序列化

有时候我们要将一个int、float、bool转成字符串,这个用boost能简单地实现,但是一些复杂的数据结构比如STL的vector、map、list、set甚至是组合的vector >、map > >数据结构,可以通过yaml库来实现序列化成字符串,下面简单地实现vector的序列化和反序列化,可以看出是支持组合嵌套的比如vector >。

template
class LexicalCast{
public:
    T operator()(const F& v){
        return boost::lexical_cast(v);
    }
};

template
class LexicalCast >{
public:
    std::vector operator() (const std::string& s){
        std::vectorv;
        std::stringstream ss;
        YAML::Node node = YAML::Load(s);
        for(int i=0; i()(ss.str()));
        }
        return v;
    }
};

template
class LexicalCast, std::string>{
public:
    std::string operator()(const std::vector& v){
        YAML::Node node(YAML::NodeType::Sequence);
        for(const auto &i : v){
            node.push_back(YAML::Load(LexicalCast()(i)));
        }
        std::stringstream ss;
        ss << node;
        return ss.str();
    }

};

 

你可能感兴趣的:(笔试题目/套题)