简体   繁体   English

如果声明了类型,则为 static_assert

[英]static_assert if a type is declared

In c++11 is it possible to cause a static_assert to fail if a type is declared.在 c++11 中,如果声明了类型,是否有可能导致 static_assert 失败。 And by declared I mean whether forward declared or fully defined.声明是指是否向前声明或完全定义。

The purpose is to fail a compile with an instructive message if something has or has not been declared already.目的是在已经或尚未声明某些内容时使用指导性消息使编译失败。

Excepting a clever trick, I fully expect that some intermediate type_traits-like template to be involved which isn't already part of the standard.除了一个聪明的技巧之外,我完全希望涉及一些中间类型的类似 type_traits 的模板,这还不是标准的一部分。

If a type does not exist at a given point in the code, then you can't refer to it there.如果在代码中的给定点不存在类型,那么您不能在那里引用它。 In order to refer to it you'd have to declare it.为了引用它,你必须声明它。 But then you can't know which declaration any use of it refers to.但是你不知道任何使用它的声明是指哪个声明。 The only possibility to effectively assert that it doesn't exist, is then to declare or define it in a way that would clash with an earlier declaration, eg like this:有效断言它不存在的唯一可能性是然后以与先前声明冲突的方式声明或定义它,例如:

struct Type;    // Earlier declaration.

// Whatever, then:
using Type = struct Unique_temporary_name*;    // "Type" must not exist.

You can statically assert that its size is what you expect.您可以静态断言它的大小是您所期望的。

typedef struct _ListNode {
    struct _ListNode* next;
    int value;
} ListNode;

static_assert(sizeof(ListNode) >= sizeof(void*) + sizeof(int));

If the type exists, this will work the same as any other static_assert(…) , if not better since this also sanity checks the size of the type.如果类型存在,这将与任何其他static_assert(…) ,如果不是更好,因为这也会检查类型的大小。 (If you didn't want that, you could simply static_assert(sizeof(ListNode) >= 1) . If the type does not exist, you will get a regular error, not an assertion failure, but I don't think that can be avoided. (如果你不想那样,你可以简单地static_assert(sizeof(ListNode) >= 1) 。如果类型不存在,你会得到一个常规错误,而不是断言失败,但我认为不能被避免。


Nit: The >= is needed due to padding bytes added by the compiler, unless you were to include #pragma pack(1). Nit:由于编译器添加了填充字节,因此需要 >=,除非您要包含 #pragma pack(1)。

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

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