【问题标题】:C++ Find element in list of tuples using predicateC ++使用谓词在元组列表中查找元素
【发布时间】:2012-03-07 15:12:43
【问题描述】:

我有一个 stl::list 元组,我想使用 std::find_if 在每个元组中使用多种类型比较来搜索元素。我可以将元组类型与特定的模板化 get() 函数相关联吗?因此不需要将字段编号传递给谓词模板。

我创建了一个这样的谓词:

template<typename T, size_t field>
struct obj_predicate : public std::unary_function<ObjectRecordType, bool>
{
    const T* comparisonObject;
    obj_predicate(const T& cObj) : comparisonObject(&cObj) {}
    bool operator()(const ObjectRecordType& obj) const
    {
        return *comparisonObject == std::tr1::get<field>(obj);
    }
};

我想要的是 obj_predicate&lt;int&gt;(3) 知道 int 在元组中的位置。

【问题讨论】:

  • 不是真的,但如果你知道解决方案,为什么不呢。
  • 你不喜欢你当前的实现吗?
  • 我有一个工厂,它通过不同类型的值创建实例。这种设计要求我重载 createInstance 方法,并使用不同的字段编号和值调用 find_if (可以在 createInstance 中使用模板类型名声明)。

标签: c++ stl tuples tr1 template-meta-programming


【解决方案1】:

我们可以使用“循环”。这将返回与给定类型的元素匹配的 last 索引。

template <typename T, typename S, int i = std::tr1::tuple_size<T>::value - 1>
struct tuple_index
{
    enum
    {
        value = std::tr1::is_same<typename std::tr1::tuple_element<i, T>::type, S>::value ?
            i :
            tuple_index<T, S, i-1>::value
    };
};

template <typename T, typename S>
struct tuple_index<T, S, -1>
{
    enum { value = -1 };
};

Example:

printf("%d\n", tuple_index<std::tr1::tuple<int, double>, int>::value);    // 0
printf("%d\n", tuple_index<std::tr1::tuple<int, double>, double>::value); // 1
printf("%d\n", tuple_index<std::tr1::tuple<int, double>, long>::value);   // -1

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-02-19
    • 1970-01-01
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多