相关疑难解决方法(0)

这会编译吗?重载分辨率和隐式转换

这个例子似乎用VC10和gcc编译(虽然我的gcc版本很老).

编辑:R.Martinho Fernandez在gcc 4.7上试过这个并且行为仍然是一样的.

struct Base
{
    operator double() const { return 0.0; }
};

struct foo
{
    foo(const char* c) {}
};

struct Something : public Base
{
    void operator[](const foo& f) {}
};

int main()
{
    Something d;
    d["32"];

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

但克朗抱怨道:

test4.cpp:19:6: error: use of overloaded operator '[]' is ambiguous (with operand types 'Something' and 'const char [3]')
    d["32"]
    ~^~~~~
test4.cpp:13:10: note: candidate function
    void operator[](const foo& f) {}
         ^
test4.cpp:19:6: note: built-in candidate operator[](long, const …
Run Code Online (Sandbox Code Playgroud)

c++ clang visual-c++ overload-resolution implicit-conversion

18
推荐指数
1
解决办法
1630
查看次数

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

考虑以下代码:

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*) …

c++

5
推荐指数
1
解决办法
245
查看次数