Boost.flyweight和Boost.MPL

时间:2011-10-20 07:17:33

标签: c++ templates boost boost-mpl

根据http://www.boost.org/doc/libs/1_40_0/libs/flyweight/test/test_basic.cpp

,根据以下定义,我有一个关于flyweight选项的问题
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::_1boost::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联系并且还不够:)

1 个答案:

答案 0 :(得分:4)

boost::mpl::_1boost::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

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

我不确定我对MPL占位符的解释非常清楚,请随时阅读excellent MPL tutorial,它解释了很好的元函数,lambda表达式和其他模板元编程功能。

相关问题