命名空间
变体
操作

std::projected

来自 cppreference.cn
< cpp‎ | iterator
 
 
迭代器库
迭代器概念
迭代器原语
算法概念和工具
间接可调用概念
通用算法要求
(C++20)
(C++20)
(C++20)
工具
projected
(C++20)
迭代器适配器
范围访问
(C++11)(C++14)
(C++14)(C++14)  
(C++11)(C++14)
(C++14)(C++14)  
(C++17)(C++20)
(C++17)
(C++17)
 
定义于头文件 <iterator>
(1)
template< std::indirectly_readable I,

          std::indirectly_regular_unary_invocable<I> Proj >
struct projected
{
    using value_type = std::remove_cvref_t<std::indirect_result_t<Proj&, I>>;
    std::indirect_result_t<Proj&, I> operator*() const; // not defined

};
(since C++20)
(until C++26)
template< std::indirectly_readable I,

          std::indirectly_regular_unary_invocable<I> Proj >

using projected = /*projected-impl*/<I, Proj>::/*__type*/; // see (3)
(since C++26)
template< std::weakly_incrementable I, class Proj >

struct incrementable_traits<std::projected<I, Proj>>
{
    using difference_type = std::iter_difference_t<I>;

};
(2) (since C++20)
(until C++26)
template< class I, class Proj >

struct /*projected-impl*/
{
    struct /*__type*/
    {
        using value_type = std::remove_cvref_t<std::indirect_result_t<Proj&, I>>;
        using difference_type = std::iter_difference_t<I>; // conditionally present

        std::indirect_result_t<Proj&, I> operator*() const; // not defined
    };

};
(3) (since C++26)
(仅为说明目的*)
1) (until C++26)别名(since C++26) 模板 projected 结合了 indirectly_readable 类型 I 和可调用对象类型 Proj,成为一个新的 indirectly_readable 类型,其引用类型是将 Proj 应用于 std::iter_reference_t<I> 的结果。
2) std::incrementable_traits 的此特化使得当 I 也是 weakly_incrementable 类型时,std::projected<I, Proj> 成为 weakly_incrementable 类型。
3) 用于避免意外的 argument-dependent lookup 的间接层。成员类型 difference_type 仅在 I 建模 weakly_incrementable 时存在。

projected 仅用于约束接受可调用对象和投影的算法,因此其 operator*() 未定义。

目录

[编辑] 模板参数

I - 一个 indirectly readable 类型
Proj - 应用于解引用 I 的投影

[编辑] 注解

间接层阻止 I 和 Proj 成为 projected 的关联类。当 I 或 Proj 的关联类是不完整类类型时,间接层避免了不必要的尝试去检查该类型的定义,从而导致硬错误。

[编辑] 示例

#include <algorithm>
#include <cassert>
#include <functional>
#include <iterator>
 
template<class T>
struct Holder
{
    T t;
};
 
struct Incomplete;
 
using P = Holder<Incomplete>*;
 
static_assert(std::equality_comparable<P>); // OK
static_assert(std::indirectly_comparable<P*, P*, std::equal_to<>>); // Error before C++26
static_assert(std::sortable<P*>); // Error before C++26
 
int main()
{
    P a[10] = {}; // ten null pointers
    assert(std::count(a, a + 10, nullptr) == 10); // OK
    assert(std::ranges::count(a, a + 10, nullptr) == 10); // Error before C++26
}

[编辑] 参见

通过投影计算 indirectly_readable 类型的 value type
(别名模板)[编辑]