gpt4 book ai didi

c++ - int 与 std::vector 的重载分辨率与单个 int 的初始化列表

转载 作者:行者123 更新时间:2023-12-05 01:50:23 25 4
gpt4 key购买 nike

为什么 c++ 选择原始类型重载匹配而不是“更好”的匹配初始化列表?


#include <vector>

void foo([[maybe_unused]] int i) {}

void foo([[maybe_unused]] const std::vector<int>& v) {}

int main() {
foo(0);
foo({1,2,3});
foo({0}); // calls foo(int) and issues a warning,
// rather than what seems like the "better"
// match foo(vector).. why?
}
<source>:10:9: warning: braces around scalar initializer [-Wbraced-scalar-init]
foo({0}); // calls foo(int) and issues a warning,
^~~

也许是“令人惊讶”的结果,因为编译器选择了它随后发出诊断的选项?

使用 Clang 14

https://godbolt.org/z/1dscc5hM4

最佳答案

{0}没有类型,所以我们需要尝试将其转换为重载集的参数类型。当考虑

void foo([[maybe_unused]] const std::vector<int>& v) {}

需要咨询[over.ics.list]/7.2哪个州

Otherwise, the implicit conversion sequence is a user-defined conversion sequence whose second standard conversion sequence is an identity conversion.

所以我们有一个用户定义的转换序列。

看着

void foo([[maybe_unused]] int i) {}

我们发现 [over.ics.list]/10.1 中涵盖了转换哪个州

if the initializer list has one element that is not itself an initializer list, the implicit conversion sequence is the one required to convert the element to the parameter type;

本例中的元素是0 , 这是一个整型字面量,是一个精确匹配标准转换

所以现在我们有一个用户定义的转换与一个标准的转换,这在 [over.ics.rank]/2.1 中有介绍。

a standard conversion sequence is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence, and

现在我们知道标准转换是更好的转换,这就是为什么 intstd::vector<int> 上选择过载过载。

关于c++ - int 与 std::vector<int> 的重载分辨率与单个 int 的初始化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73169352/

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