c++ - 类中的 static_assert 强制执行内存布局

标签 c++

我正在尝试使用 static_assert 来确保其他程序员避免扩展某个类超出其预期用途,因为它通常用于低级计算,其中假设字节数与下面的静态断言想要检查的一样.

template<typename T, int N>
class MyClass final
{
public:
    // This is the static_assert I need to fix
    static_assert(sizeof(MyClass<T, N>) == sizeof(T) * N, "Wrong size");

    // rest of code goes here... 
};

不幸的是,它不适用于:

    static_assert(std::is_standard_layout<T>::value, "Wrong Size");

因为之后仍然有可能污染类(class)。

我真的很想添加此检查,因为如果有人更改此类,即使其虚拟或添加新成员,则稍后执行代码的结果将是不确定的。

最佳答案

static_assert(sizeof(MyClass<T, N>) == sizeof(T) * N, "Wrong size");

无法在类里面工作,因为 MyClass<T, N>此时还不完整。 您可以移动static_assert进入 ctor/dtor。缺点 - 断言只会在实例化时触发。 例如

template<typename T, int N>
class MyClass final
{
public:
    static_assert(std::is_standard_layout<T>::value, "T has to provide standard layout");

    MyClass()
    {
        static_assert(sizeof(MyClass<T, N>) == sizeof(T) * N, "Wrong size");
        static_assert(std::is_standard_layout<MyClass<T, N>>::value, "MyClass has to provide standard layout");

    }
    T _m[N];
    // rest of code goes here... 
};

关于c++ - 类中的 static_assert 强制执行内存布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60246476/

相关文章:

c++ - 无法打开文件 'dxguid.lib'

c++ - 设置每个像素的最快方法

c++ - 在编译时根据字节顺序定义位域

c++ - 锁定方案黑客

c++ - 异步 glTexSubImage2D 和 OGL 线程阻塞

c++ - 无法删除 unsigned char* 数组

c++ - Linux : How to detect a process that consumes the maximum memory and kill it?

c++ - std::optional的详细信息

c++ - Visual Studio .cu 文件显示语法错误但编译成功

c++ - 如何从开放管道读取数据: example needed