Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boost.flyweight and Boost.MPL

I have a question regarding flyweight options, given the definition below, based on 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");

what value has boost::mpl::_1 and boost::mpl::_2 ? When are asigned ?

boost::mpl::_1 is most probably std::string. boost::mpl::_2 should be size_t ? If true, how is deducted ? I don't understand how is key_type chosen.

I have read http://www.boost.org/doc/libs/1_41_0/libs/flyweight/doc/tutorial/lambda_expressions.html but I it is my first contact with Boost.MPL and is not enough :)

like image 280
vlg789 Avatar asked Oct 10 '22 17:10

vlg789


1 Answers

boost::mpl::_1 and boost::mpl::_2 are placeholders; they can be used as template parameters to differ the binding to an actual argument to a later time. With this, you can do partial application (transforming a metafunction having an n-arity to a function having a (n-m)-arity), lambda expressions (creating a metafunction on-the-fly where it is needed), etc.

An expression containing at least a placeholder is a placeholder expression, which can be invoked like any other metafunction, with some arguments that will replace the placeholders.

In your example, assuming the following 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;

we can assume that at some other point in the code, the hashed_factory will be invoked with some parameter:

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

I did not look in Flyweight code, but we can suppose that _1 will be bound to the value type of the flyweight, and _2 to the key type (since it is used for hashing and testing equality). In this case, I think both will be std::string since no key type is specified.

I'm not sure my explanation about MPL's placeholders is quite clear, feel free to read the excellent MPL tutorial that explains very well metafunctions, lambda expressions and other template metaprogramming features.

like image 53
Luc Touraille Avatar answered Oct 13 '22 12:10

Luc Touraille