[mpl] Sorting types by index

I have an mpl::vector of all possible types I care about. It's called AllTypes. Given a sequence containing some subset of types in AllTypes, I want to order the sequence so that the types occur in the same relative order as in AllTypes. So if AllTypes is A, B, C, D, E and I'm given B, E, A I want to produce A, B, E Fundamentally, I'm sorting things based on their index in AllTypes. Well, that's what I want to be doing. What I'm really doing is getting compilation errors referring to a missing tag in my metafunction, which is called IndexOf. The code I'm using is below. I'd appreciate it if people would take a look and help me figure out why it's not working. Thanks, Scott #include <boost/mpl/sort.hpp> #include <boost/mpl/distance.hpp> #include <boost/mpl/find.hpp> using namespace boost; // return the index of type T in sequence S template<typename S, typename T> struct IndexOf { enum { value = mpl::distance<typename mpl::begin<S>::type, typename mpl::find<S, T>::type >::value }; }; int main() { using mpl::_1; using mpl::_2; typedef mpl::vector<char, short, int, long, float, double> AllTypes; typedef mpl::vector<long, char, short> Unsorted; typedef mpl::sort<Unsorted, // this call to mpl::less<IndexOf<AllTypes,_1>, // sort doesn't IndexOf<AllTypes,_2> > // compile >::type Sorted; }

Scott Meyers wrote:
Fundamentally, I'm sorting things based on their index in AllTypes. Well, that's what I want to be doing. What I'm really doing is getting compilation errors referring to a missing tag in my metafunction, which is called IndexOf. The code I'm using is below. I'd appreciate it if people would take a look and help me figure out why it's not working.
<snip>
// return the index of type T in sequence S template<typename S, typename T> struct IndexOf { enum { value = mpl::distance<typename mpl::begin<S>::type, typename mpl::find<S, T>::type >::value }; };
int main() { using mpl::_1; using mpl::_2;
typedef mpl::vector<char, short, int, long, float, double> AllTypes;
typedef mpl::vector<long, char, short> Unsorted;
typedef mpl::sort<Unsorted, // this call to mpl::less<IndexOf<AllTypes,_1>, // sort doesn't IndexOf<AllTypes,_2> > // compile >::type Sorted; }
Try this: template<typename S, typename T> struct IndexOf: mpl::distance<typename mpl::begin<S>::type, typename mpl::find<S, T>::type > {}; -- John Femiani

Scott Meyers writes:
John Femiani wrote:
Try this:
template<typename S, typename T> struct IndexOf: mpl::distance<typename mpl::begin<S>::type, typename mpl::find<S, T>::type > {};
Brilliant, thanks very much!
There is also (undocumented) "boost/mpl/index_of.hpp". -- Aleksey Gurtovoy MetaCommunications Engineering
participants (3)
-
Aleksey Gurtovoy
-
John Femiani
-
Scott Meyers