遍历嵌套的C ++ 11元组 [英] Traversing nested C++11 tuple

查看:105
本文介绍了遍历嵌套的C ++ 11元组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这个元组类型:



std :: tuple< int,string,std :: tuple& ,int>



如何遍历呢?



问题似乎是对于模板函数或类型的任何实现,处理嵌套元组中的所有可能的类型,必须有这种情况:

  template< typename T& 
void somefunc(T t)
{
//做某事t
}

这最终是每种类型的重载解析的最佳选择,你不能递归遍历元组,因为你失去的信息,它是一个元组。如果你试图写一个类或函数,试图确定它是一个元组还是不,你仍然跑到假情况下,具有与上述相同的问题,它结束了每个类型的匹配和元组专门版本被忽略。



有没有一种方法我不知道检查是否是一个元组?

someFunc()函数即可:

  template< typename ... Ts> 
void someFunc(const std :: tuple< Ts ...>& tuple)
{
/ *遍历元组的元素* /
traverse_tuple ;
}

template< typename T>
void someFunc(const T& value)
{
/ *使用值* /
执行某些操作

其中 traverse_tuple 是您实现的用于遍历非嵌套(平面)元组的相同函数。它为元组的每个成员调用 someFunc()

对于元组遍历函数的实现,可以检查此答案


If I have this tuple type:

std::tuple<int, string, std::tuple<...>, int>

How can I traverse it? I've been able to write functions that traverse a flat tuple, but not with nested tuples.

The problem seems to be for any implementation of a templated function or type that handles all the conceivable types in a nested tuple, there must be this case:

template<typename T>
void somefunc(T t)
{
    // Do something to t
}

Which ends up being the best choice for overload resolution for every type, and you can't recursively traverse the tuple because you lose the information that it's a tuple. If you try to write a class or function that tries to determine whether it's a tuple or not, you still run in to the "false" case which has the same problem as above in that it ends up matching for every type and the tuple specialized version gets overlooked.

Is there a way I'm not aware of to check whether something is a tuple?

解决方案

Simply overload the someFunc() function for tuples and non-tuple types:

template<typename... Ts>
void someFunc( const std::tuple<Ts...>& tuple )
{
    /* traverse the elements of the tuple */
    traverse_tuple( tuple );
}

template<typename T>
void someFunc( const T& value )
{
    /* do something with the value */
}

Where traverse_tuple is the same function you have implemented to traverse non-nested (flat) tuples. It calls someFunc() for each member of the tuple.
For an implementation of a tuple traversing function, you could check this answer.

这篇关于遍历嵌套的C ++ 11元组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆