c – 如何static_assert std :: array成员的大小

前端之家收集整理的这篇文章主要介绍了c – 如何static_assert std :: array成员的大小前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想明确关于成员变量的数组大小限制,以阻止其他人意外地进行愚蠢的更改.以下天真的尝试将无法编译:
struct Foo
{
    std::array< int,1024 > some_array;
    static_assert( (some_array.size() % 256) == 0,"Size must be multiple of 256" );
    //^ (clang) error: invalid use of non-static data member 'some_array'
};

即使std :: array :: size是constexpr,我也不能直接使用static_assert,因为函数和我的成员变量都不是静态的.

我想出的解决方案是使用decltype(因为我不想键入数组),如下所示:

static_assert( (decltype(some_array)().size() % 256) == 0,"Size must be multiple of 256" );

这看起来像是默认构造一个右值,我认为它不是一个constexpr.

为什么这样做?

有没有更简洁的方法来实现静态断言?

解决方法

because neither the function nor my member variable is static.

对.问题是静态断言不能引用非静态成员,因为some_array.size()等同于this-> some_array.size()并且在类范围内没有这个指针(仅在函数声明器内部)和默认成员初始化者).

但是,可以说decltype(array_size)因为实际上并没有尝试引用对象array_size或者调用它的成员函数,所以它只是查询类中声明的名称的类型.

This looks like it’s default-constructing an rvalue,which I didn’t think is a constexpr.

array< int,N>是一个文字类型,因此可以用常量表达式构造.你构造一个rvalue的事实并不重要,你可以构造一个文字类型,并在一个常量表达式中调用constexpr成员函数.

类似于数组< std :: string,N>不能在那里使用,因为std :: string不是文字类型,因此数组< string,N>都不是.

Is there a cleaner way to achieve the static assertion?

标准trait std :: tuple_size专门用于std :: array,所以你可以这样做:

static_assert( std::tuple_size<decltype(some_array)>::value % 256) == 0,"Size must be multiple of 256" );
原文链接:https://www.f2er.com/c/117061.html

猜你在找的C&C++相关文章