Search code examples
templatesboost-mpl

boost mpl count for simple example


I am trying to learn boost mpl, tried a very simple example to count the number of times a type appears in mpl map. Could somebody explain why the output of this program is 0

typedef map<
            pair<int, unsigned>
            , pair<char, unsigned char>
            , pair<long_<5>, char[17]>
            , pair<int[42], bool>
            > m;


    std::cout << mpl::count <
                            m,
                            mpl::key_type
                                    <
                                    m,
                                    pair<int, unsigned>
                                    >::type
                            >::type::value << std::endl;

Solution

  • According to what is written in the code you'd like to count the occurrences of type

    key_type<
        m,
        pair<int, unsigned>
    >::type
    

    in your map. In the end this is an int because in the description of mpl::key_type you'll find:

    key_type<m,x>::type          Identical to x::first;
    

    Well, so let's see what are the actual contents of your map. I could just write the type of the map, but I'd like to show you how to check a type the quick and lazy way. :P

    So, we just make the compiler fail to see whats the type of the map. I did it with adding this line somewhere:

    typename m::blaa BB;
    

    The compilation of course fails (because blaa is not an element of the mpl::map type) with following error message:

     error: 'blaa' in 'm {aka struct boost::mpl::map<boost::mpl::pair<int, unsigned int>, boost::mpl::pair<char, unsigned char>, boost::mpl::pair<mpl_::long_<5l>, char [17]>, boost::mpl::pair<int [42], bool> >}' does not name a type
    

    Ok, what we can read is that the map contains a list of pairs (e.g., boost::mpl::pair<int, unsigned int>), but no int. And in your mpl::count call you are looking for int.

    Just try to replace your std::cout lines with the following lines and you'll see that the result will be as expected.

    std::cout << 
        boost::mpl::count< m, 
            boost::mpl::pair<int, unsigned> 
        >::type::value 
    << std::endl;