【问题标题】:C++ using declarationC++ 使用声明
【发布时间】:2014-04-14 19:45:48
【问题描述】:

为什么下面的using ::foo 声明隐藏了所有其他foo 函数?

#include <iostream>

void foo(double) { std::cout << "::foo(double)" << std::endl; }

struct A {
  void foo(float) { std::cout << "A::foo(float)" << std::endl; }
  void foo(int) { std::cout << "A::foo(int)" << std::endl; }
  void foo() { std::cout << "A::foo()" << std::endl; }
};

struct B : A {
  using A::foo;
  void foo(int) { std::cout << "B::foo(int)" << std::endl; }
  void foo() { std::cout << "B::foo()" << std::endl; }

  void boo() {
    using ::foo;
    foo(1.0);
    foo(1.0f);
    foo(1);
    foo();
  };
};

int main() {
  B b;
  b.boo();
  return 0;
}

【问题讨论】:

  • 这与用于复制交换习语中的std::swap 的ADL 查找相同。 stackoverflow.com/questions/4782692/…
  • 好的,但是为什么 B::foo() 无法访问?
  • @BlazBratanic 不是,你试过B::foo()吗?
  • 你是对的。但是,为什么我需要明确指定哪个 foo 函数?在这种情况下,using 声明的全部意义都丢失了,因为我也可以调用::foo(1.0)A::foo(1.0f) 等。
  • @crashmstr:可能适用于这种情况,但是当您真的希望编译器选择时,请尝试使用足够的模板。

标签: c++


【解决方案1】:

在内部范围内的任何函数声明都会隐藏在外部范围内同名的所有函数声明。

你在函数boo函数::foo的块范围内声明

  void boo() {
    using ::foo;
    foo(1.0);
    foo(1.0f);
    foo(1);
    foo();
  };

它将所有同名函数隐藏在封闭范围内。

更准确地说。根据 C++ 标准

13 由于 using-declaration 是一个声明,因此限制 同一声明区域中的同名声明 (3.3) 也适用于 using-declarations

或者引用 C++ 标准中的以下引用可能会更好

1 using-declaration 将名称引入到声明区域 using-declaration 出现的地方。using-declaration:成员名称 在 using-declaration 中指定的声明在声明区域中声明 使用声明出现在其中。

【讨论】:

    猜你喜欢
    • 2022-06-03
    • 2012-06-22
    • 2020-07-17
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 2021-05-01
    相关资源
    最近更新 更多