gpt4 book ai didi

c++ - std::vector 范围构造函数可以调用显式转换吗?

转载 作者:行者123 更新时间:2023-12-01 17:46:29 24 4
gpt4 key购买 nike

下面的程序格式正确吗?

#include <vector>
struct A {
explicit A(int) {}
};
int main() {
std::vector<int> vi = {1, 2, 3, 4, 5};
std::vector<A> va(vi.begin(), vi.end());
}

根据 C++17 [sequence.reqmts],要求

X u(i, j);

其中X是序列容器,是:

T shall be EmplaceConstructible into X from *i.

但是,在上一段中指出:

i and j denote iterators satisfying input iterator requirements and refer to elements implicitly convertible to value_type,

因此,在我看来,这两个要求都需要满足:范围的值类型必须可以隐式转换为容器的值类型, EmplaceConstructible 必须满足(这意味着分配器必须能够执行所需的初始化)。由于 int 不能隐式转换为 A,因此该程序应该是格式错误的。

然而,令人惊讶的是,it seems to compile under GCC .

最佳答案

仅要求序列容器支持从满足隐式可转换性标准的迭代器进行构造。

据我所知,这本身并不禁止序列容器支持不满足该标准的迭代器的构造1。有明确的规则:

If the constructor ... is called with a type InputIterator that does not qualify as an input iterator, then the constructor shall not participate in overload resolution.

目前尚不清楚“作为输入迭代器的资格”在上下文中的确切含义。它是表达 Cpp17InputIterator 的非正式方式,还是试图引用 i 和 j 的要求?我不知道。无论允许与否,标准对于检测都没有严格的要求:

[container.requirements.general]

The behavior of certain container member functions and deduction guides depends on whether types qualify as input iterators or allocators.The extent to which an implementation determines that a type cannot be an input iterator is unspecified, except that as a minimum integral types shall not qualify as input iterators. ...

根据任何 Cpp17InputIterator“有资格作为输入迭代器”的解释,示例程序不需要格式错误。但也不能保证其格式良好。

1在这种情况下,依赖它时可能会被视为实现质量问题并发出警告。另一方面,对隐式转换的这种限制可以被视为 defect .

<小时/>

附注在 Clang(使用 libc++)和 Msvc 中编译时也不会出现警告。

P.P.S。这个措辞似乎是在 C++11 中添加的(这是很自然的,因为当时还引入了显式构造函数)。

关于c++ - std::vector 范围构造函数可以调用显式转换吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58647874/

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