Boost logo

Boost Users :

From: David Abrahams (dave_at_[hidden])
Date: 2004-12-23 12:52:10


David Greene wrote:
> Well, my mpl adventure continues.
>
> I'm trying to place pair members of a sequence with their keys:
>
> #include <boost/type_traits.hpp>
> #include <boost/mpl/pair.hpp>
> #include <boost/mpl/key_type.hpp>
> #include <boost/mpl/map.hpp>
> #include <boost/mpl/vector.hpp>
> #include <boost/mpl/replace_if.hpp>
> #include <boost/mpl/int.hpp>
>
> #include <iostream>
> #include <typeinfo>
>
> using namespace boost;
> using namespace boost::mpl;
>
> struct pair_base {};
>
> template<typename Key, typename Value>
> struct pair_type : public pair<Key, Value>, private pair_base {};
>
> template<typename Sequence>
> struct replaceit {
> typedef typename replace_if<
> Sequence,
> is_base_and_derived<pair_base, _>,
> key_type<map<>, _>
> >::type type;
> };
>
> int main(void)
> {
> replaceit<
> vector<
> charm

You should be seeing a syntax error right here.

> pair_type<int, int_<32> >,
> pair_type<long, int_<64> >
> double
> >
> >::type toprint;
>
> std::cout << typeid(toprint).name() << std::endl;
>
> return(0);
> };
>
> I know this is incorrect because the pairs will be replaced by
> the key_type metafunction itself.
>
> If I add ::type to the end of key_type<map<>, _> the compiler
> complains that no ::first member exists:

>
> What's the right way to do this?

Use an algorithm like transform that _computes_ the new values rather
than simply replacing them with a constant value:

template <class Seq>
struct replaceit
  : transform<
        Seq
      , if_<
            is_base_and_derived<pair_base,_>
          , key_type<map<>,_>
          , _
>
>
{};

> Furthermore, is there a better way to identify pairs in
> replace_if than deriving from a special class? All I can
> think of is writing a predicate class and specializing it
> for mpl::pair<U, V>. Seems like there should be an easier
> way.

Why? That seems like a pretty darned good approach to me.

-- 
Dave Abrahams
Boost Consulting
http://www.boost-consulting.com

Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net