我有一个元组的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
在元组中的位置。
我们可以使用"循环"。这将返回与给定类型的元素匹配的最后一个索引。
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("%dn", tuple_index<std::tr1::tuple<int, double>, int>::value); // 0
printf("%dn", tuple_index<std::tr1::tuple<int, double>, double>::value); // 1
printf("%dn", tuple_index<std::tr1::tuple<int, double>, long>::value); // -1