如何通过地址获取元组中元素的索引? [英] How to get the index of an element in a tuple via address?
本文介绍了如何通过地址获取元组中元素的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
例如:
std::tuple<int, double> t;
void* p = &std::get<1>(t);
现在我想通过一些函数获得p的索引,例如
Now I want to get p's index by some function like
template<typename... Ts>
size_t index(void* p, std::tuple<Ts...> const& t)
{
...
}
当然这个例子的结果是1。
Sure the result is 1 for this example. I am interested in how to implement the function to get the index when p is obtained by ways other than the explicit index.
推荐答案
我有兴趣实现这个函数来获取索引,而不是显式索引。在C ++ 14中,你不需要一个迷你索引库:
Something you do not need in C++14, a mini indexes library:
template<unsigned...>struct indexes{using type=indexes;};
template<unsigned Cnt,unsigned...Is>
struct make_indexes:make_indexes<Cnt-1,Cnt-1,Is...>{};
template<unsigned...Is>
struct make_indexes<0,Is...>:indexes<Is...>{};
template<unsigned Cnt>
using make_indexes_t=typename make_indexes<Cnt>::type;
实际工作的功能。创建数组指针到元素。然后搜索 p
。 nullptr
和 -1
使其适用于空元组。
Function that does actual work. Creates an array pointers-to-elements. Then searches for p
. The nullptr
and -1
make it work for empty tuples.
template<unsigned...Is,class Tuple>
unsigned index_of(indexes<Is...>,void const* p, Tuple const&t){
void const* r[]={ nullptr, &std::get<Is>(t)... };
auto it = std::find( std::begin(r), std::end(r), p );
if (it==std::end(r))
return -1;
else
return (it-std::begin(r))-1;
}
你可以把它放在 c $ c>命名空间。
you can put that in a details
namespace.
最后一个函数:
template<class...Ts>
unsigned index_of( void const*p, std::tuple<Ts...> const& t ){
return index_of( make_indexes_t<sizeof...(Ts)>{}, p, t );
}
return unsigned(-1)
失败。
return unsigned(-1)
on failure.
这篇关于如何通过地址获取元组中元素的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文