C++使用谓词在元组列表中查找元素

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

我有一个 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<int>(3)知道 int 的位置在元组中。

最佳答案

我们可以使用“循环”。这将返回与给定类型的元素匹配的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

关于C++使用谓词在元组列表中查找元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9604017/

相关文章:

c++ - Fortify SCA 基于可执行文件或 .o 文件构建

c++ - 用于清理 vector 破坏的模板 - 怎么做?

C++ 类 vector 推回错误

c++ - 什么是 std::mbstate_t?

python - 打印两个元组之间的差异

python - 用 Python 中的元组值计算两个字典的点积

c++ - RAII 资源处理

c++ - 函数原型(prototype)中的 const 参数

c++ - 迭代器类型的模板

c++ - std::get 在给定 6 个整数的元组时失败