我有一个 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 };
};
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/