【问题标题】:C++ ambiguous call to functions in different namespacesC++ 对不同命名空间中函数的模糊调用
【发布时间】:2012-04-19 19:18:03
【问题描述】:

这个问题让我和一些同事感到困惑,但我们已经验证这是针对大约 5 种不同编译器的错误。他们都返回这个小代码-sn-p是“模棱两可的”。

namespace foo {
  struct type_t {
    int x;
  };
  void bar( type_t & );
}

void bar( foo::type_t & );

void func( void ) {
  foo::type_t x = { 10 };
  bar(x);
}

Clang 返回以下内容:

func.cpp:12:3: error: call to 'bar' is ambiguous
  bar(x);
  ^~~
func.cpp:5:8: note: candidate function
  void bar( type_t & );
       ^
func.cpp:8:6: note: candidate function
void bar( foo::type_t & );
     ^
1 error generated.

为什么会这样?代码中没有“使用”语句。解析顺序不应该包含 foo 命名空间,那么为什么要在那里搜索呢?为什么会这样模棱两可?

【问题讨论】:

  • 了解ADL,又名 Koenig 查找。
  • 在 gcc 中:ideone.com/G4uHo
  • 这似乎不是编译器错误。 g++、HP C++ 和 Comeau 也会产生类似的错误。
  • @daxelrod 这是标准行为。
  • 嗨乔纳森,我注意到这个问题仍然悬而未决。还有什么不清楚的地方吗?

标签: c++ filenames


【解决方案1】:

它是argument dependent lookupbar 的参数位于 foo 命名空间中,因此 bar 也在该命名空间中查找,从而导致歧义。如果您想从全局命名空间中调用foo,请明确调用::foo

【讨论】:

  • 是的,使用“descoping”操作符:::bar() 修复它:)
猜你喜欢
  • 1970-01-01
  • 2012-11-12
  • 1970-01-01
  • 1970-01-01
  • 2017-05-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-12
相关资源
最近更新 更多