【问题标题】:Does a using-declaration only import overloads declared above the using-declaration?using-declaration 是否仅导入在 using-declaration 之上声明的重载?
【发布时间】:2012-05-17 14:40:22
【问题描述】:

例如 GCC 和 clang 都无法编译如下代码:

struct S {};

namespace N
{
    void g(S);
}

using N::g;

namespace N
{
    void g(int);
}

int main()
{
    g(0);
}

出现错误:

test.cpp: In function 'int main()':
test.cpp:17:8: error: could not convert '0' from 'int' to 'S'
     g(0);
        ^

建议 using-declaration 仅导入在 using-declaration 出现的位置高于声明的重载,而不是稍后可能出现的重载(但在使用名称之前)。

这种行为正确吗?

【问题讨论】:

    标签: c++ namespaces scope overloading using-declaration


    【解决方案1】:

    这种行为正确吗?

    是的,这种行为是正确的,并且按照 c++ 标准进行了很好的定义。

    相关部分是 C++11 标准的§ 7.3.3.11

    由 using-declaration 声明的实体应根据 using-declaration 处的定义在使用它的上下文中为人所知。在使用该名称时,不考虑在 using 声明之后添加到命名空间的定义。

    [ Example:    
        namespace A {
            void f(int);
         }
        using A::f; // f is a synonym for A::f;
        // that is, for A::f(int).
        namespace A {
            void f(char);
        }
        void foo() {
            f(’a’); // calls f(int),
        } // even though f(char) exists.
        void bar() {
            using A::f; // f is a synonym for A::f;
            // that is, for A::f(int) and A::f(char).
            f(’a’); // calls f(char)
        }
     —end example ]
    

    【讨论】:

      猜你喜欢
      • 2015-10-16
      • 2015-07-24
      • 2017-01-25
      • 1970-01-01
      • 2011-08-28
      • 2015-09-22
      • 2022-12-03
      • 1970-01-01
      • 2015-10-08
      相关资源
      最近更新 更多