Is it possible to use compile time asserts in C++

你离开我真会死。 提交于 2019-12-11 04:52:38

问题


I want to use a template for some data processing, but I need the code to be more or less safe when ported.

This might be a problem if sizes of variables grow beyond anticipated values, so I would like to assert at compile time that some assumptions are still valid.

For example, sizeof(long)>sizeof(int), so that if this assumption fails, I could break the build.

I know that standard mandates that long>=int, but this is just an example, don't concentrate on the variable types.


回答1:


C++11 has static_assert:

static_assert(sizeof(long) > sizeof(int), "long must be greater than int");

On older compilers you can use Boost.StaticAssert.

BOOST_STATIC_ASSERT(sizeof(long) > sizeof(int));


来源:https://stackoverflow.com/questions/10866767/is-it-possible-to-use-compile-time-asserts-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!