【问题标题】:Getting the index of boost::fusion::vector from a boost::mpl::vector从 boost::mpl::vector 获取 boost::fusion::vector 的索引
【发布时间】:2010-10-01 17:01:14
【问题描述】:

我开始使用 boost fusion 和 mpl 库,但遇到了一个非常简单的问题。

我声明了以下类型:

typedef boost::mpl::vector<char, int, long>   TypeVector;
typedef boost::fusion::vector<char, int, long> FusionVector_t;

现在我想编写一个函数,从 FusionVector 中获取值。

template<size_t N typename T>
T getValue(FusionVector_t fvec)
{
    return boost::fusion::at_c<N>(fvec);
}

该函数按预期工作,但我想从 boost::mpl 向量中获取索引并在此函数中使用它,而不是将其作为模板参数传递给函数。 但到目前为止我还没有弄清楚如何做到这一点。

有人可以给我一个提示吗?

【问题讨论】:

    标签: c++ boost boost-mpl boost-fusion


    【解决方案1】:

    您可以使用 find 算法来获得一个“迭代器”,该“迭代器”指向一个类型在 MPL 序列中的第一次出现。比如:

    typedef boost::mpl::find<TypeVector, T>::type MplIter;
    

    然后在那个“迭代器”的位置查询融合向量:

    return boost::fusion::at_c<MplIter::pos::value>(fvec);
    

    但是,我根本不明白您为什么使用 MPL 向量。 IIUC,您想将 getValue 定义为:

    template<class T>
    T getValue(FusionVector_t fvec)
    {
      typedef boost::mpl::find<TypeVector, T>::type MplIter;
      return boost::fusion::at_c<MplIter::pos::value>(fvec);
    }
    

    只有在 TypeVector 和 FusionVector_t “包含”相同的类型序列时才能工作。既然如此,何不只用FusionVector_t写:

    template<class T>
    T getValue(FusionVector_t fvec)
    {
      return *boost::fusion::find<T>(fvec);
    }
    

    此外,如果您想使用“T”作为 Fusion 序列中的“索引”,这仅在给定类型在序列中仅出现一次时才有意义。因此,fusion::set 似乎比向量更合适。在这种情况下,您将拥有:

    typedef boost::fusion::set<char, int, long> FusionSet_t;
    
    template<class T>
    T getValue(FusionSet_t fset)
    {
      return boost::fusion::at_key<T>(fset);
    }
    

    【讨论】:

    • 感谢您的提示。 MPL 和融合向量是相同的。但是你的方法似乎比我的要干净得多。我使用 fusion::vector 的原因也是因为我来自元组库。但我会坚持你的建议。非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多