zoukankan      html  css  js  c++  java
  • Boost.Any

    支持类型安全地存储和获取任意类型的值

    #include <list>
    #include <boost/any.hpp>
    #include <string>
    #include <iostream>
    
    typedef std::list<boost::any> many;
    
    void append_int(many & values, int value)
    {
      boost::any to_append = value;
      values.push_back(to_append);
    }
    
    void append_string(many & values, const std::string & value)
    {
      values.push_back(value);
    }
    
    void append_char_ptr(many & values, const char * value)
    {
      values.push_back(value);
    }
    
    void append_any(many & values, const boost::any & value)
    {
      values.push_back(value);
    }
    
    void append_nothing(many & values)
    {
      values.push_back(boost::any());
    }
    
    
    bool is_empty(const boost::any & operand)
    {
      return operand.empty();
    }
    
    bool is_int(const boost::any & operand)
    {
      return operand.type() == typeid(int);
    }
    
    bool is_char_ptr(const boost::any & operand)
    {
      try
      {
        boost::any_cast<const char *>(operand);
        return true;
      }
      catch(const boost::bad_any_cast &)
      {
        return false;
      }
    }
    
    bool is_string(const boost::any & operand)
    {
      return boost::any_cast<std::string>(&operand);
    }
    
    void count_all(many & values, std::ostream & out)
    {
      out << "#empty == "
        << std::count_if(values.begin(), values.end(), is_empty) << std::endl;
      out << "#int == "
        << std::count_if(values.begin(), values.end(), is_int) << std::endl;
      out << "#const char * == "
        << std::count_if(values.begin(), values.end(), is_char_ptr) << std::endl;
      out << "#string == "
        << std::count_if(values.begin(), values.end(), is_string) << std::endl;
    }
    
    int main()
    {
      many values;
    
      append_int(values, 3);
      append_any(values, 4);
      append_char_ptr(values, "abc");
      append_string(values, std::string("abc"));
      append_int(values, 5);
      std::string str = "def";
      append_string(values, str);
      append_any(values, str);
      append_nothing(values);
    
      count_all(values, std::cout);
      return 0;
    }

     

  • 相关阅读:
    混合开发的坑(3) ---关于es6
    混合开发的坑(2) ---pdf展示
    混合开发的坑(1) ---ajax请求
    vue.js
    vue中 import引入组件
    vue中 静态文件引用注意事项
    Oracle 数据库链接
    Oracle中的NVL,NVL2,NULLIF以及COALESCE函数使用
    Merge into 使用
    C# —— IList, ArrayList与List的区别详解
  • 原文地址:https://www.cnblogs.com/chenkkkabc/p/3200395.html
Copyright © 2011-2022 走看看