gpt4 book ai didi

C++ 对重载函数的奇怪模棱两可的调用

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:54:59 25 4
gpt4 key购买 nike

<分区>

首先,这个问题纯属理论性质。我不是在寻找解决方案(我已经知道了),我只是在寻找解释。

以下代码无法编译:

struct foo {};
void a(foo) {}
namespace foobar {
void a(foo) {}
void b(foo f) {a(f);}
}
int main() {return 1;}

MSVC++:

1>c:\projects\codetests\main.cpp(7) : error C2668: 'foobar::a' : ambiguous call to overloaded function
1> c:\projects\codetests\main.cpp(4): could be 'void foobar::a(foo)'
1> c:\projects\codetests\main.cpp(2): or 'void a(foo)' [found using argument-dependent lookup]
1> while trying to match the argument list '(foo)'

G++:

main.cpp: In function 'void foobar::b(foo)':
main.cpp:5:20: error: call of overloaded 'a(foo&)' is ambiguous
main.cpp:5:20: note: candidates are:
main.cpp:4:7: note: void foobar::a(foo)
main.cpp:2:6: note: void a(foo)

编译此代码时(MSVC++ 和 G++):

namespace bar {struct foo {};}
void a(bar::foo) {}
namespace foobar {
void a(bar::foo) {}
void b(bar::foo f) {a(f);}
}
int main() {return 1;}

这是为什么呢? foo 周围的命名空间在这里为编译器改变了什么?这种行为是否在 C++ 标准中定义?还有其他解释吗?谢谢。

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