【发布时间】:2021-12-28 01:25:38
【问题描述】:
我起草了代码来找出元组元素中类型为 V 的值的索引。 一般来说,代码可以工作,但元组的完美前锋似乎不起作用。 请参考 main 函数中的最后两行注释。
#include <type_traits>
#include <iostream>
#include <tuple>
#include <cxxabi.h>
template<int ...INDEX>
struct Sequence
{
};
template<int N, int ...MORE>
struct MkSequence
{
using type = typename MkSequence<N-1, N-1, MORE...>::type;
};
template<int ... LEFT>
struct MkSequence<0, LEFT...>
{
using type = Sequence<LEFT...>;
};
template<typename Tuple, int I, typename V>
bool equal(Tuple &&t, V&& v, typename std::enable_if<std::is_same<typename std::tuple_element<I,Tuple>::type, V>::value >::type* = nullptr)
{
return std::get<I>(std::forward<Tuple>(t)) == std::forward<V>(v);
};
template<typename Tuple, int I, typename V>
bool equal(Tuple &&t, V&& v, typename std::enable_if<!std::is_same<typename std::tuple_element<I,Tuple>::type, V>::value>::type* = nullptr)
{
return false;
}
template<typename Tuple, typename V, int ...I>
int tupleIndexOfWithSeq(Tuple &&t, V&& v, Sequence<I...>)
{
bool list[] = {(equal<Tuple,I,V>(std::forward<Tuple>(t),std::forward<V>(v)))...};
int i = 0;
for(auto v: list)
{
if(v) return i;
i++;
}
return -1;
};
template<typename Tuple, typename V>
int tupleIndexOf(Tuple &&t, V&& v)
{
return tupleIndexOfWithSeq(std::forward<Tuple>(t), std::forward<V>(v), typename MkSequence<std::tuple_size<Tuple>::value>::type{});
};
int main()
{
using TP = std::tuple<int, std::string>;
TP t(1, "hello");
std::string str="hello";
std::cout<<tupleIndexOf(TP(1, "hello"), str)<<std::endl;
//Why the following calling of tupleIndexOf does not compile:
//std::cout<<tupleIndexOf(t, str)<<std::endl;
};
【问题讨论】:
标签: c++ c++11 templates tuples forwarding-reference