Boost.flyweight和Boost.MPL

vlg*_*789 5 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");
Run Code Online (Sandbox Code Playgroud)

什么价值boost::mpl::_1boost::mpl::_2?什么时候被签名?

boost::mpl::_1最有可能的std::string.boost::mpl::_2应该是size_t?如果是真的,如何扣除?我不明白key_type是如何选择的.

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

Luc*_*lle 4

boost::mpl::_1boost::mpl::_2是占位符;它们可以用作模板参数,以区分稍后与实际参数的绑定。这样,您可以进行部分应用(将具有 n 元数的元函数转换为具有 (nm) 元数的函数)、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;
Run Code Online (Sandbox Code Playgroud)

我们可以假设在代码中的某个其他点,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
Run Code Online (Sandbox Code Playgroud)

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

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