【问题标题】:How does a using-declaration reduce the names available for lookup without ADL?using-declaration 如何在没有 ADL 的情况下减少可用于查找的名称?
【发布时间】:2016-02-07 10:44:54
【问题描述】:
#include <iostream>
#include <string>

class X {};

namespace N
{

std::string to_string(X)
{
    return "foo";
}

void foo()
{
    //using std::to_string; // will break the build if uncommented...
    //using N::to_string;   // ...unless this is uncommented as well
    std::cout << to_string(X()) << std::endl;
}

}

int main()
{
    N::foo();
    return 0;
}

要么我偶然发现了许多我不掌握的 C++ 奥秘之一,要么我在这里遗漏了一些明显的东西。

using std::to_string 如何明显将在非限定查找期间可用的名称集减少到仅可通过 ADL 访问的名称集?虽然我可以猜到问题可能是 to_string(X) 被声明在与 X 不同的命名空间中,但我不禁注意到,如果没有 using std::to_string,N::to_string(X) 可以通过使用“普通",我习惯的直观查找规则。

【问题讨论】:

    标签: c++ namespaces argument-dependent-lookup name-lookup


    【解决方案1】:

    这不是特定于 using 声明,而是遵循正常的范围规则。当你在函数中引入一个名字时,它会从外部范围中隐藏同名的东西。

    您也可以在foo 中拥有一个int to_string; 局部变量。这也会隐藏N::to_string。

    【讨论】:

    • 然而,我注意到与声明 int to_string 的类比并不总是成立:事实上,using std::to_string 并没有隐藏在 @ 中声明的 to_string(X) 函数987654327@ 的命名空间要从 ADL 中找到,而 int to_string 会导致编译器错误。如果我声明一个std::string to_string(int),类比成立,例如,在foo() 内。
    • 是的,情况不同。 ADL 将使编译器从参数的关联命名空间中考虑一个函数,即使它不会以其他方式看到。但问题中的代码并非如此,因为X 在命名空间之外。
    猜你喜欢
    • 2015-10-16
    • 2021-07-09
    • 2020-10-01
    • 2011-02-11
    • 2012-05-01
    • 1970-01-01
    • 2018-07-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多