【问题标题】:Why does a constructor which takes iterators require elements to be EmplaceConstructible?为什么带有迭代器的构造函数要求元素是 EmplaceConstructible?
【发布时间】:2016-03-22 12:52:05
【问题描述】:

我在标准 (n4296)、23.2.3/4 (表 100) 中看到了对序列 stl 容器的要求,并阅读了一个采用参数迭代器(X - 容器,i 和 j - 输入迭代器)的构造函数)

X(i, j)
X a(i, j)

要求容器的元素类型是 EmplaceConstructible。

Requires: T shall be EmplaceConstructible into X from *i

我认为可以通过为范围内的每个迭代器调用 std::allocator_traits::construct (m, p, *it) 方法来实现构造函数(其中 m - A 类型的分配器,p - 指向内存的指针,它- [i; j) 中的迭代器,并且元素只有 CopyInsertable 概念是必需的,因为只为复制/移动提供了一个参数,而 EmplaceConstructible 概念需要从一组参数构造元素。这个决定有什么理由吗?

【问题讨论】:

    标签: c++ c++11 stl c++14 c++-concepts


    【解决方案1】:

    CopyInsertable 是一个二元概念 - 给定一个容器 X 它适用于单个类型 T,它需要有一个复制构造函数。但是,*i 可以是与T 不同的类型,只要有办法(隐式)从*i 构造T

      char s[] = "hello world!";
      std::vector<int> v(std::begin(s), std::end(s));
      // int is EmplaceConstructible from char
    

    T 不是 CopyInsertable 的(人为的)示例:

    struct nocopy {
      nocopy(int) {}
      nocopy(nocopy const&) = delete;
      nocopy(nocopy&&) = delete;
    };
    int a[]{1, 2, 3};
    std::vector<nocopy> v(std::begin(a), std::end(a));
    

    【讨论】:

    • s/隐式/显式/。 allocator_traits::construct 是直接初始化的,并且会很乐意为您进行显式转换,无论好坏。
    猜你喜欢
    • 2014-09-18
    • 2015-07-18
    • 2011-10-27
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 1970-01-01
    • 1970-01-01
    • 2022-08-11
    相关资源
    最近更新 更多