简体   繁体   English

防止别名重新定义C ++

[英]Prevent alias to alias redefinition C++

I want hide library implementation from user and provide public API with aliasing of implementation, to reduce code duplication. 我希望从用户隐藏库实现,并提供具有实现别名的公共API,以减少代码重复。 So if I have two logically different API structs, but they implementation is equal, implementation would be aliased as shown in code snippet. 因此,如果我有两个逻辑上不同的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;
}  

But it may lead to hidden logical errors if user decide to redefine alias to library public API as in code snippet, because it compiles just fine. 但是,如果用户决定在代码片段中重新定义库公共API的别名,则可能会导致隐藏的逻辑错误,因为它编译得很好。 So the question is: 所以问题是:

Is it possible to prevent alias to alias redefinition if redefined aliases are referenced to the same types? 如果重新定义的别名被引用到相同的类型,是否可以防止别名重新定义别名?

If you point to the same type, the compiler is totally fine with that, and I am afraid you cannot do anything against that. 如果你指向相同的类型,那么编译器完全没问题,我担心你不能做任何事情。

From the typedef keyword which, in your case, is essentially equivalent to the using keyword: 来自typedef关键字,在您的情况下,它基本上等同于using关键字:

https://en.cppreference.com/w/cpp/language/typedef 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). Typedef不能用于更改现有类型名称的含义(包括typedef-name)。 Once declared, a typedef-name may only be redeclared to refer to the same type again. 声明后,只能重新声明typedef-name以再次引用相同的类型。

So, it is an error to re-declare a typedef-name with a different type-id . 因此,重新声明具有不同type-id的typedef-name是错误的。 It does nothing to re-declare a typedef-name with the same type-id . 它没有重新声明具有相同type-id的typedef-name。

The easiest fix might be inheritance: 最简单的修复可能是继承:

struct A1 : public impl::A
{
  using A::A;
};
struct A2 : public impl::A
{
  using A::A;
};

This defines new types, but reuses the implementation. 这定义了新类型,但重用了实现。 You could even use private inheritance but that will require more using declarations for other members. 您甚至可以使用私有继承,但这需要更多using其他成员的声明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM