命名空间
变体
操作

`std::list` 的推导指引

来自 cppreference.cn
< cpp‎ | container‎ | list
 
 
 
 
定义于头文件 <list>
template< class InputIt,

          class Alloc = std::allocator<
              typename std::iterator_traits<InputIt>::value_type> >
list( InputIt, InputIt, Alloc = Alloc() )

    -> list<typename std::iterator_traits<InputIt>::value_type, Alloc>;
(1) (since C++17)
template< ranges::input_range R,

          class Alloc = std::allocator<ranges::range_value_t<R>> >
list( std::from_range_t, R&&, Alloc = Alloc() )

    -> list<ranges::range_value_t<R>, Alloc>;
(2) (since C++23)
1) 此推导指引为 list 而提供,以允许从迭代器范围推导。此重载仅在 InputIt 满足 LegacyInputIterator 且 Alloc 满足 Allocator 时参与重载决议。
2) 此推导指引为 list 而提供,以允许从 std::from_range_t 标签和 input_range 推导。

注意:库确定类型不满足 LegacyInputIterator 的程度是未指定的,但至少整型不符合输入迭代器的条件。同样地,库确定类型不满足 Allocator 的程度是未指定的,但至少成员类型 Alloc::value_type 必须存在,且表达式 std::declval<Alloc&>().allocate(std::size_t{}) 在被视为未求值操作数时必须是良构的。

[编辑] 注释

特性测试宏 标准 特性
__cpp_lib_containers_ranges 202202L (C++23) 范围感知构造与插入;重载 (2)

[编辑] 示例

#include <list>
#include <vector>
 
int main()
{
    std::vector<int> v = {1, 2, 3, 4};
 
    // uses explicit deduction guide to deduce std::list<int>
    std::list x(v.begin(), v.end());
 
    // deduces std::list<std::vector<int>::iterator>
    // first phase of overload resolution for list-initialization selects the candidate
    // synthesized from the initializer-list constructor; second phase is not performed
    // and deduction guide has no effect
    std::list y{v.begin(), v.end()};
}