【发布时间】:2021-04-15 13:57:29
【问题描述】:
采取以下措施:
foo.h
#ifndef FOO_H
#define FOO_H
#include <stdint.h>
enum directions {
NORTH,
EAST,
SOUTH,
WEST
};
bool foo_a(uint16_t a);
bool foo_b(enum directions a);
#endif //FOO_H
foo.cpp
#include "foo.h"
#include <iostream>
namespace test {
bool foo_a(uint16_t a) {
return a < 22;
}
bool foo_b(enum directions a) {
return a < WEST;
}
bool foo(void) {
return foo_a(16) || foo_b(NORTH);
}
}
int main(void)
{
std::cout << test::foo();
return 0;
}
如果我们尝试编译它,我们会得到错误:
g++ foo.cpp
foo.cpp: In function ‘bool test::foo()’:
foo.cpp:17:40: error: call of overloaded ‘foo_b(directions)’ is ambiguous
15 | return foo_a(16) || foo_b(NORTH);
| ^
foo.cpp:12:10: note: candidate: ‘bool test::foo_b(directions)’
10 | bool foo_b(enum directions a) {
| ^~~~~
In file included from foo.cpp:2:
foo.h:14:6: note: candidate: ‘bool foo_b(directions)’
14 | bool foo_b(enum directions a);
|
因此编译器会抱怨foo_b 重载,但不会抱怨foo_a 重载。为什么它完全抱怨foo_b?为什么它不只选择这个命名空间中的那个?为什么enum 的处理方式与uint16_t 不同(foo_a 没有错误)?
【问题讨论】:
-
ADL 最有可能应用于枚举函数,但由于
uint16_t最有可能映射到内置类型,因此不会发生 ADL。 -
@Eljay 我知道如何解决它,这是为什么让我感到困惑的问题。
-
啊,好吧。内森奥利弗所说的。由于 ADL,
foo_b不明确。foo_a不是由于 ADL 而产生歧义,因为 ADL 不适用。
标签: c++ enums namespaces