c++ - 如果使用 {},函数调用不会产生歧义

标签 c++ initialization c++17 curly-braces list-initialization

#include <stdio.h>
#include <vector>
#include <deque>

// 1st function
void f(int i, int j = 10){
    printf("Hello World what");
};

void f(std::vector<int>){
    printf("Hello World vec");
};

void f(std::deque<int>){
    printf("Hello World deq");
};

int main()
{
    f({});
    return 0;
}
如果第一个函数被注释掉,我会得到 ambiguous call编译时。如果没有注释掉,则调用第一个函数。为什么是 {}隐式转换为 int ?
现场示例:https://onlinegdb.com/rkhR0NiBD

最佳答案

Why is {} implicitly converted to int?


这是 copy-list-initialization ,作为参数值初始化(零初始化)的效果为 0 . int可以从(空)braced-init-list 初始化,就像 int i{};int i = {}; .
  1. in a function call expression, with braced-init-list used as an argument and list-initialization initializes the function parameter

对于 f(std::vector<int>)f(std::deque<int>)要调用,需要用户定义的转换(由 std::vectorstd::deque 的构造函数取 std::initializer_list );那么第一个重载在重载决议中获胜。

关于c++ - 如果使用 {},函数调用不会产生歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64061910/

相关文章:

c++ - 如何让定时器在后台保持运行

c++ - std::clamp - 检测函数返回值是否绑定(bind)到 const T&

c++ - 在搜索代表任何字符的单词时使用问号

c++ - librdkafka:rd_kafka_assignment返回分配的分区的偏移量-1001

c++ - 如何默认初始化 C++ 中内置类型的局部变量?

c++ - 在重载的 operator new 中初始化类成员是否未定义?

C++在复制构造函数中初始化列表赋值并在复制构造函数中崩溃

c++ - 为什么这个简单的 C++ 不起作用?

c++ - 我的函数没有进入for循环,不知道为什么

c++ - _Not_fn 函数调用运算符的 noexcept 说明符