如何避免“operator[](const char*)”歧义?

riv*_*riv 5 c++

考虑以下代码:

class DictionaryRef {
public:    
  operator bool() const;
  std::string const& operator[](char const* name) const;

  // other stuff
};

int main() {
  DictionaryRef dict;
  char text[256] = "Hello World!";

  std::cout << dict[text] << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

当使用 G++ 编译时,会产生以下警告:

class DictionaryRef {
public:    
  operator bool() const;
  std::string const& operator[](char const* name) const;

  // other stuff
};

int main() {
  DictionaryRef dict;
  char text[256] = "Hello World!";

  std::cout << dict[text] << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我知道这意味着什么(并且原因已在operator[](const char *) ambiguity中进行了解释),但我正在寻找一种方法来确保正确的行为/解决警告而不改变我的类设计 - 因为它非常有意义一个类同时具有布尔转换和[](const char*)运算符。

除了生成随机编译器警告之外还有什么目的operator[](long int, char*)?我无法想象有人1["hello"]用真正的代码编写。

Tob*_*ght 0

虽然你“无法想象有人1["hello"]用真正的代码编写”,但这是合法的 C++,这是[]从 C 继承的交换律的结果。无论合理与否,这就是语言的定义方式,并且不太可能改变我们。

避免歧义的最好方法是添加explicit布尔转换 - 我们很少需要非显式的operator bool().

另一种方法是替换operator bool()为 an operator void*(),它仍然满足布尔测试,但不会转换为整数。