c++ - 前向迭代器的重载

标签 c++ templates iterator overloading libc++

在研究 libc++ 时,我发现当模板参数是前向迭代器时,有两种不同的函数重载方法。

第一种方法是使用 std::iterator_traits::iterator_category

template <class ForwardIter1, class ForwardIter2>
inline
bool
__some_function(ForwardIter1 first1, ForwardIter1 last1,
                ForwardIter2 first2, ForwardIter2 last2,
                std::forward_iterator_tag, std::forward_iterator_tag)
{
    // do stuff ...

    return true;
}


template <class InputIter1, class InputIter2>
inline
bool
__some_function(InputIter1 first1, InputIter1 last1,
                InputIter2 first2, InputIter2 last2,
                std::input_iterator_tag, std::input_iterator_tag)
{
    // do stuff ...

    return true;
}


template <class InputIter1, class InputIter2>
inline
bool
some_function(InputIter1 first1, InputIter1 last1,
              InputIter2 first2, InputIter2 last2)
{
    return __some_function(first1, last1, first2, last2,
                           typename std::iterator_traits<InputIter1>::iterator_category(),
                           typename std::iterator_traits<InputIter2>::iterator_category());
}

但我也看到了 std::enable_if

的用法
template <class ForwardIter1, class ForwardIter2>
inline
bool
some_function(ForwardIter1 first1, ForwardIter1 last1,
              ForwardIter2 first2, ForwardIter2 last2,
              typename std::enable_if<
                  __is_forward_iterator<ForwardIter1>::value &&
                  __is_forward_iterator<ForwardIter2>::value
              >::type* = 0)
{
    // do stuff ...

    return true;
}


template <class InputIter1, class InputIter2>
inline
bool
some_function(InputIter1 first1, InputIter1 last1,
              InputIter2 first2, InputIter2 last2,
              typename std::enable_if<
                  __is_exactly_input_iterator<InputIter1>::value &&
                  __is_exactly_input_iterator<InputIter2>::value
              >::type* = 0)
{
    // do stuff ...

    return true;
}

这两种方法中哪一种是解决问题的“首选”方法,还是取决于具体情况。在那种情况下,什么时候一种解决方案会比另一种更好?

最佳答案

更好的方法是使用 enable if 作为返回类型,这样就不需要传递任何额外的参数(具有默认值)来运行:

template <class ForwardIter1, class ForwardIter2>
typename std::enable_if
<
    __is_forward_iterator<ForwardIter1>::value
    &&
    __is_forward_iterator<ForwardIter2>::value
,   bool
>::type
some_function
(
    ForwardIter1 first1, ForwardIter1 last1
,   ForwardIter2 first2, ForwardIter2 last2
)
{
    // do stuff ...
    return(true);
}

双下划线的标识符也是保留的,但我们假设 __is_forward_iterator 模板是有效的并且存在于某处。

关于c++ - 前向迭代器的重载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47272321/

相关文章:

c++ - long long int 不太好用 long int

c++ - 错误 C2065 : undeclared identifier in template function

c++ - 类模板状态数据成员,而不是可以显式特化的实体

c++ - 使用迭代器访问成员字符串时出错::空

c++ - 为什么 vector::pop_back 会使迭代器 (end() - 1) 无效?

ruby - 从 Ruby 中的对象数组中提取嵌套对象数组的最快方法是什么?>

c++ - 两个非常大的数的除法

c++ - 如果我不将预写的字符串保存到变量中,它是否还在内存中?

c++ - 这个可变参数模板代码有什么作用?

c++ - 将带有可变参数构造函数的对象放入映射中