gpt4 book ai didi

c++ - iterator_traits SFINAE 友好性

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:50:04 28 4
gpt4 key购买 nike

阅读 excerpt 时来自 cppreference

If Iterator does not have the five member types difference_type, value_type, pointer, reference, and iterator_category, then this template has no members by any of those names (std::iterator_traits is SFINAE-friendly)

我自然而然地认为这意味着每个成员类型在迭代器本身中定义时就被定义了。但是你瞧,这实际上意味着如果定义了所有五个,那么它们就被定义了。

struct defined
{
using difference_type = int;
using value_type = int;
using pointer = int*;
using reference = int&;
using iterator_category = std::input_iterator_tag;
};

struct undefined
{
using value_type = int;
};

template<typename T>
using value_type = typename std::iterator_traits<T>::value_type;

void foo()
{
using std::experimental::is_detected_v;
static_assert(is_detected_v<value_type, defined>);
static_assert(!is_detected_v<value_type, undefined>);
}

Live

这是为什么?如果他们彼此独立,我会认为它会更友好。例如,如果算法只需要将 value_type 存储在某处而不关心其他任何事情。

template<typename It>
auto amazingfy(It first, It last)
{
typename std::iterator_traits<It>::value_type v;
for(; first != last; first++)
v += *first;
return v;
}

它将无法在某些仅定义 value_type 的迭代器上编译,但有趣的是,如果它是 typename It::value_type v;

则编译成功

最佳答案

可以从相应的提案中收集一些见解 N3844 :

With benefit of hindsight, it has from time to time been argued that the SGI STL (and consequently C++98) erred in specifying iterator_traits as a bundle of five type aliases, and that individual iterator-related traits would have been a better design. Even if true, this paper proposes no change to the basic bundled design, keeping to an all-or-nothing principle.

所以看起来它只是试图非常谨慎地处理当前情况,并进行最少的更改以使特征对 SFINAE 友好。选择性地包含成员会导致定义不明确的特征,显然,这被认为是一个可能影响深远的结果。

关于c++ - iterator_traits SFINAE 友好性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49260285/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com