如何将迭代器限制为正向迭代器? [英] How to restrict an iterator to being a forward iterator?

查看:165
本文介绍了如何将迭代器限制为正向迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数需要枚举迭代器多次,但根据MSDN

I have a function that needs to enumerate an iterator multiple times, but according to MSDN, "Once you increment any copy of an input iterator, none of the other copies can safely be compared, dereferenced, or incremented thereafter."

现在我有类似的东西:

template<typename It, typename TCallback /*signature: bool(value_type)*/>
bool EnumerateTwice(const It &begin, const It &end, TCallback callback)
{
    for (It it = begin; it != end; ++it)
        if (!callback(*it))
            return false;
    for (It it = begin; it != end; ++it)
        if (!callback(*it))
            return false;
    return true;
}

但没有任何限制 It 为正向迭代器。

but nothing restricts It to being a forward iterator.

如何将这种限制放在模板函数上? (C ++ 03)

How do I place that restriction on the templated function? (C++03)

推荐答案

您可以使用SFINAE并替换 bool by:

You can use SFINAE and replace bool by:

typename enable_if<
   is_same<typename std::iterator_traits<It>::iterator_category,
           std::forward_iterator_tag>::value,
   bool>::type

您可能需要定义 is_same enable_if 你自己,如果你不想从Boost或TR1中拉取它们:

You may need to define is_same and enable_if yourself if you don't want to pull them from Boost or TR1:

template <typename A, typename B>
struct is_same { static const bool value = false; };

template <typename T>
struct is_same<T, T> { static const bool value = true; };

template <bool, typename> struct enable_if { };
template <typename T> struct enable_if<true, T> { typedef T type; };

这篇关于如何将迭代器限制为正向迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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