5

我有一个关于享元选项的问题,给出下面的定义,基于http://www.boost.org/doc/libs/1_40_0/libs/flyweight/test/test_basic.cpp

typedef boost::flyweights::flyweight<
    std::string, 
    boost::flyweights::tag<int>,
    boost::flyweights::static_holder_class<boost::mpl::_1>,          
    boost::flyweights::hashed_factory_class<
        boost::mpl::_1, 
        boost::mpl::_2, 
        boost::hash<boost::mpl::_2>,
        std::equal_to<boost::mpl::_2>,
        std::allocator<boost::mpl::_1>
    >,
    boost::flyweights::simple_locking,
    boost::flyweights::refcounted
> StringFlyweight;

StringFlyweight    test1("Hello World");

boost::mpl::_1和有什么价值boost::mpl::_2?什么时候分配?

boost::mpl::_1很可能是std::stringboost::mpl::_2应该是size_t?如果属实,如何扣除?我不明白 key_type 是如何选择的。

我已阅读http://www.boost.org/doc/libs/1_41_0/libs/flyweight/doc/tutorial/lambda_expressions.html但这是我第一次接触 Boost.MPL 并且还不够:)

4

1 回答 1

4

boost::mpl::_1并且boost::mpl::_2是占位符;它们可以用作模板参数,以便稍后将绑定与实际参数不同。有了这个,您可以进行部分应用(将具有 n-arity 的元函数转换为具有 (nm)-arity 的函数)、lambda 表达式(在需要的地方即时创建元函数)等。

至少包含一个占位符的表达式是一个占位符表达式,它可以像任何其他元函数一样被调用,并带有一些将替换占位符的参数。

在您的示例中,假设以下 typedef

typedef boost::flyweights::hashed_factory_class<
    boost::mpl::_1, 
    boost::mpl::_2, 
    boost::hash<boost::mpl::_2>,
    std::equal_to<boost::mpl::_2>,
    std::allocator<boost::mpl::_1>
> hashed_factory;

我们可以假设在代码中的某个其他点,hashed_factory将使用一些参数调用:

typedef typename
    boost::mpl::apply<
       hashed_factory,
       X,
       Y
    >::type result; // invoke hashed_factory with X and Y
                    // _1 is "replaced" by X, _2 by Y

我没有查看享元代码,但我们可以假设_1它将绑定到享元的值类型和_2键类型(因为它用于散列和测试相等性)。在这种情况下,我认为两者都会,std::string因为没有指定密钥类型。

我不确定我对 MPL 占位符的解释是否很清楚,请随意阅读优秀的 MPL 教程,该教程很好地解释了元函数、lambda 表达式和其他模板元编程特性。

于 2011-10-20T07:33:06.843 回答