08年06月10日

Posted on 2008-06-10 17:27 RichardHe 阅读(138) 评论(0)  编辑 收藏 引用
boost any库(转)
    1. 可容纳许多可能值类型的类型,比如int和string,并且可在它们之间自由
转换,例如:将5作为"5"或者反之。这样的类型在脚本语言和其他的解释型语言中
较常见。boost::lexical_cast支持这种转换功能。
    2. 含有不同类型的值但并不试图在它们之间进行转换的可区分类型,即5严格
地作为一个int存放,不能隐式转换为"5"或者5.0。它们不关心解释,而关心有效
的类型安全性,是单一值的范型容器,不会产生有歧义的转换。
    3. 不可区分的类型,可以引用任何实际的类型,由程序员来保证所有形式的
访问和解释。C++中的void*提供了这样的功能,同时它也会导致不确定的行为。
   
    any类(基于Kevlin Henney在"Valued Conversions"中所述的同名类)是一个
基于第二类的可变值类型。它支持任意值类型的复制和有安全检查的提取。一个提
供更多合适的运算符的类似设计,可用作一个一般的函数适配器any_function,一
个一般的迭代器适配器any_iterator等等。
例子

    下面的代码说明使用隐式转换/复制到any对象的语法:

#include <list>
#include <boost/any.hpp>

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());
}

下面的判断谓词接着前面的定义,说明了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
    {
        any_cast<const char *>(operand);
        return true;
    }
    catch(const boost::bad_any_cast &)
    {
        return false;
    }
}

bool is_string(const boost::any & operand)

{
    return 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;
}

下面的类型源自OMG的属性服务,为任意值类型定义了名字-值对:

struct property
{
    property();
    property(const std::string &, const boost::any &);

    std::string name;
    boost::any value;
};

typedef std::list<property> properties;

下面的基类说明了基于回调的运行时多态性的实现方法,其中的回调函数拥有任意
类型的参数。由于C++中缺少虚函数模板,不同的实现方法需要在效率,安全性和
通用性之间作权衡。使用一个带类型检查的可变类型提供了一种解决途径:

class consumer
{
public:
    virtual void notify(const any &) = 0;
    ...
};


只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理


posts - 94, comments - 138, trackbacks - 0, articles - 94

Copyright © RichardHe