c++ - 这个名称解析如何与实现函数和回退函数一起工作?

标签 c++ metaprogramming

我正在从事的一个项目需要为多个目标进行编译。每个目标的底层实现可能会有所不同,因为设备需要以不同方式配置硬件。

为了强制目标实现遵循接口(interface)/设计契约系统,我们设计了这个系统。如果目标没有相应地实现所述接口(interface),则会在使用时抛出错误。

以下代码使用 gcc、arm-none-eabi-gcc 和 clang 进行测试

namespace A {
    namespace C {
        void foo() {}
    }
}

namespace B {
    using namespace A::C;
    void foo() {}
}

using namespace A;
namespace C {

}

int main() {
    B::foo(); // ok
    C::foo(); // won't compile
    return 0;
}

现在在推理为什么这段代码会编译或不编译时会出现多个问题:

为什么编译器不报告 A::foo(bool) 和 B::set(bool) 之间 Unresolved 歧义?

为什么 C::foo() 编译,因为我的理论是实现了相同的命名结构,但方式不同:

最佳答案

为什么编译器不报告 target::set(bool) 和 interface_contracts::set(bool) 之间 Unresolved 歧义?

在第一个代码片段中,名称 hwstl::target::pin::set隐藏姓名 hwstl::interface_contracts::pin::set .

来电hwstl::device::pin::set(true); , 名称查找在找到 hwstl::target::pin::set 时停止.只有一个候选函数,没有歧义。

来电hwstl::unsatisfied_device::pin::set(true); , 只有一个函数叫做 set无论如何都可以找到。

10.3.4.1 A using-directive does not add any members to the declarative region in which it appears.

为什么下面的代码编译不通过?

在第二个代码片段中,您调用了 set按合格 ID:hwstl::unsatisfied_device::pin::set ,编译器只会尝试在命名空间 hwstl::unsatisfied_device::pin 中查找名称.因此它无法找到 using 指令引入的名称 using namespace interface_contracts;在它之外。

这是您的代码的简化版本:

namespace A {
    void foo() {}
}

namespace B {
    using namespace A;
    void foo() {}
}

using namespace A;
namespace C {

}

int main() {
    B::foo(); // ok
    C::foo(); // won't compile
    return 0;
}

关于c++ - 这个名称解析如何与实现函数和回退函数一起工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53377320/

相关文章:

c++ - 通过 curl 通过 http 发送和接收字符串

c++ - `T&` 和 `const T&` 对于 all-const 类的区别

c++ - 为什么会出现段错误 (C++ 98)?

c++ - 是否所有运算符重载都将运算符放在将调用其重载的对象之后?

c++ - <function number of lines> 和 <times function called> 是否被认为与内联成反比?

ruby-on-rails - 自动创建缺失的连接模型

scala - `this` 关键字的 Scala 类型编程类比是什么?

c++ - 预处理/预编译 - 用常量替换变量

elixir - 在 Elixir 中用宏中的行为实现协议(protocol)

python使用内部类动态创建类