【问题标题】:assert that struct type is declared with alignas()断言结构类型是用 alignas() 声明的
【发布时间】:2020-04-12 12:33:30
【问题描述】:

正如标题所述,我需要某种方式来断言已使用 alignas 声明了一个类型:

struct alignas(16) MyStruct {
    ...
};

它用于模板参数,模板类需要确保其模板化的类型是 16 字节对齐的。

【问题讨论】:

    标签: c++ assert alignas


    【解决方案1】:

    您可以使用alignof 来确保您获得的类型与正确的大小对齐。你会在你的函数中使用它,比如

    template <typename T>
    void foo(const T& bar)
    {
        static_assert(alignof(T) == 16, "T must have an alignment of 16");
        // rest of function
    }
    

    如果在课堂上使用它,你会拥有

    template <typename T>
    class foo
    {
        static_assert(alignof(T) == 16, "T must have an alignment of 16");
        // rest of class
    };
    

    【讨论】:

    • 你也可以直接去alignof,省去很多打字的麻烦。 alignofalignas同时引入。
    猜你喜欢
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 2014-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-30
    相关资源
    最近更新 更多