代码:
#include <stdint.h>
struct HashType64
{
inline HashType64(uint64_t h) noexcept : _h(h) {}
inline operator uint64_t() const noexcept { return _h; }
inline operator int64_t() const = delete;
inline operator int32_t() const = delete;
inline operator uint32_t() const = delete;
private:
uint64_t _h;
};
uint64_t f() {
return HashType64(0) & 0xFFULL;
}
错误:
<source>: In function 'uint64_t f()':
<source>:17:26: error: ambiguous overload for 'operator&' (operand types are 'HashType64' and 'long long unsigned int')
17 | return HashType64(0) & 0xFFULL;
| ~~~~~~~~~~~~~ ^ ~~~~~~~
| | |
| HashType64 long long unsigned int
<source>:17:26: note: candidate: 'operator&(uint32_t {aka unsigned int}, long long unsigned int)' (built-in)
17 | return HashType64(0) & 0xFFULL;
| ~~~~~~~~~~~~~~^~~~~~~~~
<source>:17:26: note: candidate: 'operator&(int32_t {aka int}, long long unsigned int)' (built-in)
<source>:17:26: note: candidate: 'operator&(int64_t {aka long int}, long long unsigned int)' (built-in)
<source>:17:26: note: candidate: 'operator&(uint64_t {aka long unsigned int}, long long unsigned int)' (built-in)
我明白错误的原因,但不明白为什么会发生这个错误。`HashType64`只能转换为`uint64_t`类型,而不能转换为其他整数类型,其他重载函数都不适用,为什么会出现歧义呢?
= delete
的意思是使用该函数/运算符是错误的,而不是编译器应该使用另一个函数。与void f(int); void f(double) = delete;
相比,这意味着f(1.0)
应该失败,而不是使用int
重载。 - BoP= delete
的意思是使用该函数/运算符是错误的,而不是编译器应该使用另一个函数。与void f(int); void f(double) = delete;
相比,这意味着f(1.0)
应该失败,而不是使用int
重载。 - BoP= delete
的意思是使用该函数/运算符是错误的,而不是编译器应该使用另一个函数。与void f(int); void f(double) = delete;
相比,这意味着f(1.0)
应该失败,而不是使用int
重载。 - undefined