我可以在“初始化器太少"上导致编​​译错误吗?

Can I cause a compile error on quot;too few initializersquot;?(我可以在“初始化器太少上导致编​​译错误吗?)

本文介绍了我可以在“初始化器太少"上导致编​​译错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用聚合初始值设定项为单元测试设置静态数据块.

I am using an aggregate initializer to set up a block of static data for a unit test.

我想使用数组大小​​作为预期的元素数,但如果提供的初始值设定项太少,这可能会失败:

I would like to use the array size as the expected number of elements, but this can fail if too few initializers are provided:

my_struct_type expected[14] =
{
    { 1.234, 0, 'c' },
    { 3.141, 1, 'z' },
    { 2.718, 0, 'a' }
};

这不会在 Visual Studio 2008 中产生编译器错误.

This gives no compiler error in Visual Studio 2008.

我希望能够这样使用它:

I would like to be able to use it as such:

const unsigned expected_size = sizeof(expected) / sizeof(my_struct_type);

BOOST_CHECK_EQUAL(points.size(), expected_size);

for( int i = 0; i < expected_size; i++ )
{
    BOOST_CHECK_EQUAL(points[i].value, expected[i].value);
    BOOST_CHECK_EQUAL(points[i].count, expected[i].count);
    BOOST_CHECK_EQUAL(points[i].sym,   expected[i].sym);
}

但是因为我没有 14 点的编译时保证,这会从 数组的末尾 提供的值的末尾运行到默认初始化的值中.

but because I don't have a compile-time guarantee of 14 points, this runs off the end of the array end of the provided values and into the default-initialized values.

我可以在编译时以某种方式强制执行聚合数组初始值设定项的数量吗?

Can I somehow enforce the number of aggregate array initializers at compile-time?

推荐答案

第一:可能会有警告.你试过在最高警告级别编译吗?

First: There might be a warning for this. Have you tried compiling at the highest warning level?

然后:如果交换哪个值是计算值和哪个是文字值,则可能会引发编译时错误:

Then: If you swap which value is calculated and which is literal, you could raise a compile-time error:

my_struct_type my_array[] = // <== note the empty []
{
    { 1.234, 0, 'c' },
    { 3.141, 1, 'z' },
    { 2.718, 0, 'a' }
};

BOOST_STATIC_ASSERT( sizeof(my_array)/sizeof(my_array[0]) == 14 );

这篇关于我可以在“初始化器太少"上导致编​​译错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:我可以在“初始化器太少"上导致编​​译错误吗?

基础教程推荐