确定(c ++)迭代器是否相反 [英] Determine if a (c++) iterator is reverse

查看:142
本文介绍了确定(c ++)迭代器是否相反的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个机制来确定在编译时是否迭代器是否反转。

I want a mechanism to determine in compile time whether an iterator is reverse or not.

迭代器特征 只能帮助迭代器类型的类别,而我需要的是以下行:

Iterator traits can only help with the category of an iterator type and what I need is something in the lines of:

template<typename IterType>
struct IsReverseIterator
{
    enum { Yes = /* Implementation of the mechanism */ };
}

我有一个解决方案, >虽然,容器类型也必须提供:

I have a solution, that has a small drawback though, the container type has to be provided as well :

typedef char     TrueT;
typedef struct { TrueT _[2]; } FalseT;

template<typename Cont> TrueT  IsReverseIterator(typename Cont::const_reverse_iterator);    
template<typename Cont> FalseT IsReverseIterator(...);

它显然使用SFINAE,可以像这样使用:

It uses SFINAE obviously and can be utilized like so :

std::vector<int> v;

std::cout << (sizeof(IsReverseIterator<std::vector<int>>(v.begin())) ==  sizeof(TrueT)) << std::endl;
std::cout << (sizeof(IsReverseIterator<std::vector<int>>(v.rbegin())) ==  sizeof(TrueT)) << std::endl;    

任何想法?

EDIT

为了解释我要搜索的内容,以下面的代码为例

To explain what I'm searching for, take for example the following code

template<typename Cont, typename It>
bool points_to_last_element(Cont const &container, It iter)
{
    return iter == container.rend(); 
    // here I would like to dispatch to 2 implementations
    // one for reverse iterators and one for forward where this would happen
    // return iter == container.end();
}

这是一个假的例子,请不要抓住这个事实我已经处理它或者我可以有两个重载,一个采取 Cont :: reverse_iterator 和一个采取 Cont :: iterator 。我不/不能改变这种设计,我只是试图一个更优雅的方式(如果有任何)在内部处理它。我再次重申,这是一个假的例子。

It is a dummy example, please don't get caught on the fact that the code I have already handles it or that I could have two overloads, one taking Cont::reverse_iterator and one taking Cont::iterator. I don't/can't change that design, I'm just trying a more elegant way (if there's any) to handle it internally. Again I repeat that was a dummy example.

推荐答案

#include <iterator>
#include <type_traits>

template<typename Iter>
struct is_reverse_iterator : std::false_type { };

template<typename Iter>
struct is_reverse_iterator<std::reverse_iterator<Iter>>
: std::integral_constant<bool, !is_reverse_iterator<Iter>::value>
{ };

您还可以为任何用户定义的反向迭代器迭代器专门化trait。

You could also specialize the trait for any user-defined iterators that are reverse iterators.

这篇关于确定(c ++)迭代器是否相反的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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