【问题标题】:boost::mpl::vector - getting to a type's base-offsetboost::mpl::vector - 获取类型的基本偏移量
【发布时间】:2011-05-18 11:32:50
【问题描述】:

在对mpl::vector 执行mpl::find<seq,type> 之后,是否可以得到它的偏移量?

换一种说法,我想做以下等价的编译时间:

#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;
}

如果不这样做,我在mpl::vector 中的类型有一个type_trait&lt;T&gt;::ordinal const 硬编码,如果可能的话,我想避免这种情况。

重要提示,我还从向量创建了一个boost::variant,我发现我可以通过执行运行时函数variant::which() 来获得序数。但是,这需要我创建一个具有默认初始化值的虚拟对象。这是相当难看的。如果您知道使用变体的其他方法,那也可以解决我的问题。

【问题讨论】:

    标签: c++ algorithm containers boost-mpl template-meta-programming


    【解决方案1】:

    如果您正在寻找的是一种 indexOf 功能,我想 Boost.MPL 文档中关于 find 的示例可以解决问题:

    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 );
    

    【讨论】:

    • aah 一个iter 有一个pos 元素?我在迭代器概念文档boost.org/doc/libs/1_46_1/libs/mpl/doc/refmanual/… 中找不到它
    • 虽然我在查看迭代器概念文档时找不到 pos 成员,但它显示在 mpl::find 文档的示例中(与您显示的代码片段相同) .
    • @Hassan Syed:您可能对这个问题及其关于undocumented iter::pos的答案都感兴趣
    【解决方案2】:

    它们是迭代器类别中的一个元函数,它被称为distance

    ps,很抱歉这么快就回答了我自己的问题。我只是偶然发现了解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-12
      • 1970-01-01
      相关资源
      最近更新 更多