编译时检查以确保结构中的任何地方都没有填充 [英] Compile-time check to make sure that there is no padding anywhere in a struct

查看:85
本文介绍了编译时检查以确保结构中的任何地方都没有填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以编写一个编译时断言来检查某种类型是否有填充?

Is there a way to write a compile-time assertion that checks if some type has any padding in it?

例如:

struct This_Should_Succeed
{
    int a;
    int b;
    int c;
};

struct This_Should_Fail
{
    int a;
    char b;
    // because there are 3 bytes of padding here
    int c;
};

推荐答案

自C ++ 17起,您可能可以使用

Since C++17 you might be able to use std::has_unique_object_representations.

#include <type_traits>

static_assert(std::has_unique_object_representations_v<This_Should_Succeed>); // succeeds
static_assert(std::has_unique_object_representations_v<This_Should_Fail>); // fails

尽管如此,这可能无法完全满足您的要求.检查链接的cppreference页面以获取详细信息.

Although, this might not do exactly what you want it to do. Check the linked cppreference page for details.

这篇关于编译时检查以确保结构中的任何地方都没有填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆