C++超载分辨率将初始化器列表作为参数

问题描述 投票:0回答:1

有人可以解释为什么两种情况都打印“普通int”?

#include <iostream>

void f(const int (&)[2])

{std::cout<<"int array"<<std::endl;}

void f(const int&)

{std::cout<<"plain int"<<std::endl;}

int main() {

    f({2}); 
    // case 1: print "plain int"

    f({});  
    // case 2: print "plain int"
    
    return 0;

}
我期望这些案件模棱两可。

c++ c++17 overload-resolution
1个回答
0
投票
当撑杆为空时,编译器将首先搜索任何将接受默认可构造的POD(普通旧数据)的签名,该签名是签名/未签名的短/长/长int,float或double。

例如:

void f(const int (&)[2])

程序输出:

#include <iostream> void f(const int (&)[2]) { std::cout << "&void f(int(&)[2])\n"; } void f(float) { std::cout << "&void f(float)\n"; } // adding another overload accepting a POD will result in // an ambiguous function call, and so will not compile. // ex: void f(int) { std::cout << "&void f(int)\n"; } int main() { f({}); // the best match is f(POD{}) -> f(float) f({2}); // here, 2 is an int so best match is -> f({2, 0}) f({1, 2}); // -> f({1, 2}) }

您可以在这里与其他类型一起玩:
https://godbolt.org/z/b7qbwy64n


最新问题
© www.soinside.com 2019 - 2025. All rights reserved.