c++ - 防止别名到别名重新定义 C++

标签 c++ c++11 c++14

我想对用户隐藏库实现并提供带有实现别名的公共(public) API,以减少代码重复。因此,如果我有两个逻辑上不同的 API 结构,但它们的实现相同,则实现将使用别名,如代码片段所示。

// library implementation
namespace impl {
    struct A {};
}

// library public API
using A1 = impl::A;
using A2 = impl::A;

// library usage
int main(int argc, char* argv[]) {
    using type = A1;
    // do some stuff
    using type = A2; // prevent this redefinition with reporting warning or error
    // do some more stuff
    return 0;
}  

但是如果用户决定像在代码片段中那样重新定义库公共(public) API 的别名,它可能会导致隐藏的逻辑错误,因为它编译得很好。所以问题是:

如果重新定义的别名被引用到相同的类型,是否可以防止别名到别名的重新定义?

最佳答案

如果您指向同一类型,编译器完全可以接受,恐怕您对此无能为力。

来自 typedef 关键字,在您的情况下,它本质上等同于 using 关键字:

https://en.cppreference.com/w/cpp/language/typedef

Typedef cannot be used to change the meaning of an existing type name (including a typedef-name). Once declared, a typedef-name may only be redeclared to refer to the same type again.

因此,用不同的 type-id 重新声明 typedef-name 是错误的。它不会重新声明具有相同 type-id 的 typedef-name。

关于c++ - 防止别名到别名重新定义 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51839774/

相关文章:

c++ - 正确删除单例

c++ - 返回一堆值的接口(interface)

c++ - undefined reference `pthread_create' 使用 ASIO 和 std::thread 制作 C++11 应用程序时出错

c++ - 未使用的模板类型定义的同时参数包扩展错误

c++ - 模板实例化和带有 unique_ptr 的 pimpl 习语

c++ - 使用模板参数包解析一行文本

c++ - 可变线程与非常量方法

c++ - 使用结构模板的结构模板

c++ - 为什么在转换/复制 vector 时进行这么多复制

c++ - 我可以在 lambda 捕获子句中声明一个变量吗?