【CPP】模板偏特化

注意事项:

1.首先要定义通用模板类,再定义特化的模板类

2.特化的模板类是处理复杂数据类型的,如vector,list,set,unordered_set,map,unordered_map。如果处理的还是简单类型数据,就会引起对自己的循环调用。

#include <iostream>
#include <yaml-cpp/yaml.h>
#include <boost/lexical_cast.hpp>
#include <boost/bind.hpp>
#include <string>
#include <vector>
#include <sstream>

static void ListAllMember(const std::string& prefix,
                          const YAML::Node& node,
                          std::list<std::pair<std::string, const YAML::Node> >& output) {
    if(prefix.find_first_not_of("abcdefghikjlmnopqrstuvwxyz._012345678")//检查非法字符,空字符是合法字符
            != std::string::npos) {
        std::cout << "Config invalid name: " << prefix << " : " << node;
        return;
    }
    output.push_back(std::make_pair(prefix, node));//第一个prefix是“”,表示永远也取不到最大的node
    if(node.IsMap()) {//如果当前节点是Map节点,就要继续遍历其中的小节点
        for(auto it = node.begin();
                it != node.end(); ++it) {
            ListAllMember(prefix.empty() ? it->first.Scalar()
                    : prefix + "." + it->first.Scalar(), it->second, output);
        }
    }
}

static void LoadFromYaml(const YAML::Node& root) {
    std::list<std::pair<std::string, const YAML::Node> > all_nodes;
    ListAllMember("", root, all_nodes);

    for(auto& i : all_nodes) {//遍历检查,用引用来访问
        std::string key = i.first;
        if(key.empty()) {
            continue;
        }

        std::stringstream ss;
        ss << i.second;
        std::cout << ss.str() << std::endl;
        //if(var) {
        //    if(i.second.IsScalar()) {
        //        var->fromString(i.second.Scalar());
        //    } else {
        //        std::stringstream ss;
        //        ss << i.second;
        //        var->fromString(ss.str());
        //    }
        //}
    }
}

template <typename F, typename T>
class LexicalCast {
public:
    T operator()(const F& val) {
        return boost::lexical_cast<T>(val);
    }
};

template <typename T>
class LexicalCast<std::vector<T>, std::string> {//在<>里也有两种类型,并且不能跟对象名称
public:
    std::string operator()(const std::vector<T>& vec) {
        YAML::Node node_class(YAML::NodeType::Sequence);
        for(auto& i : vec) {
            node_class.push_back(LexicalCast<T, std::string>()(i));//使用的时候一定要多加()
        }
        std::stringstream ss;
        ss << node_class;
        return ss.str();
    }
};

int main()
{
    YAML::Node node = YAML::Load("[22,3,4,4]");
    std::cout << node[0] << std::endl;
    //YAML::Node root = YAML::LoadFile("./robot.yaml");
    //LoadFromYaml(root);
    std::vector<int> vec = {10, 11, 12, 13};
    std::cout << LexicalCast<std::vector<int>, std::string>()(vec) << std::endl;//使用的时候一定要多加()
    return 0;
}
发布了36 篇原创文章 · 获赞 6 · 访问量 6994

猜你喜欢

转载自blog.csdn.net/zhuikefeng/article/details/104513146
今日推荐