我可以在“太少的初始化程序”上导致编​​译错误吗? [英] Can I cause a compile error on "too few initializers"?

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

问题描述

我使用一个聚合初始化器来为单元测试设置一个静态数据块。

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.

我想能够使用它:

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?

推荐答案

第一:可能有警告。

然后:如果你交换哪个值被计算,哪个是字面值,你可能会引发一个编译时错误:

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 );

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

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