4

Is it possible to get at the offset of a mpl::vector after performing a mpl::find<seq,type> on it ?

Put differently I want to do the compile time equavalent of:

#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
  typedef std::vector<int> v_type;
  v_type v_int(3);

  v_int[0] = 1;
  v_int[1] = 2;
  v_int[2] = 3;

  v_type::iterator it= std::find(  v_int.begin() ,v_int.end(),3);

  std::cout << it - v_int.begin() << std::endl;
}

Failing this, my types in mpl::vector have a type_trait<T>::ordinal const hard-coded, I would like to avoid this if possible.

Important Note, I am also creating a boost::variant from the vector, and I see I can get at the ordinal by performing a runtime function variant::which(). However, this requires I create a dummy object with default-initialized values. This is quite uggly. If you know some other way of doing it with variant, that would be a solution to my problem as well.

Hassan Syed
  • 20,075
  • 11
  • 87
  • 171

2 Answers2

3

If what you're looking for is a kind of indexOf feature, I guess the example from Boost.MPL doc concerning find will do the trick:

typedef vector<char,int,unsigned,long,unsigned long> types;
typedef find<types,unsigned>::type iter;

BOOST_MPL_ASSERT(( is_same< deref<iter>::type, unsigned > ));
BOOST_MPL_ASSERT_RELATION( iter::pos::value, ==, 2 );
mister why
  • 1,967
  • 11
  • 33
  • aah an `iter` has a `pos` element ? I couldn't find it in the itterator concepts documentation http://www.boost.org/doc/libs/1_46_1/libs/mpl/doc/refmanual/iterators-concepts.html – Hassan Syed May 18 '11 at 11:50
  • Whilst I couldn't find a `pos` member when I was looking at the iterator concept documentation, it is shown in an example of the `mpl::find` documentation (same code fragment as you have shown). – Hassan Syed May 18 '11 at 11:58
  • @Hassan Syed: you might be interested in both this question and its answer regarding [undocumented iter::pos](http://stackoverflow.com/questions/5666394/is-mpl-pos-an-undocumented-metafunction) – mister why May 18 '11 at 12:04
1

Their is a metafunction in the itterator category to do just this, it is called distance.

p.s., apologies for answering my own question so quickly. I just stumbled on the solution.

Community
  • 1
  • 1
Hassan Syed
  • 20,075
  • 11
  • 87
  • 171