static_assert 有什么作用,你会用它做什么? [英] What does static_assert do, and what would you use it for?

查看:27
本文介绍了static_assert 有什么作用,你会用它做什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你能举一个例子,说明 static_assert(...) ('C++11') 可以优雅地解决手头的问题吗?

我熟悉运行时assert(...).什么时候我应该更喜欢 static_assert(...) 而不是常规的 assert(...)?

另外,在boost中有一个叫做BOOST_STATIC_ASSERT的东西,它和static_assert(...)一样吗?

解决方案

离我而去...

#include "SomeLibrary.h"static_assert(SomeLibrary::Version > 2,"旧版本的 SomeLibrary 缺少 foo 功能.无法继续!");类 UsingSomeLibrary {//...};

假设 SomeLibrary::Version 被声明为静态常量,而不是被 #defined 声明(正如人们在 C++ 库中所期望的那样).

与必须实际编译 SomeLibrary 和您的代码、链接所有内容并仅运行可执行文件然后相比,您会发现您花了 30 分钟编译了不兼容的版本SomeLibrary.

@Arak,回应你的评论:是的,你可以让 static_assert 坐在任何地方,从它的外观来看:

class Foo{民众:静态常量 int bar = 3;};static_assert(Foo::bar > 4, "Foo::bar 太小 :(");int main(){返回 Foo::bar;}

<前>$ g++ --std=c++0x a.cppa.cpp:7: 错误:静态断言失败:Foo::bar 太小 :("

Could you give an example where static_assert(...) ('C++11') would solve the problem in hand elegantly?

I am familiar with run-time assert(...). When should I prefer static_assert(...) over regular assert(...)?

Also, in boost there is something called BOOST_STATIC_ASSERT, is it the same as static_assert(...)?

解决方案

Off the top of my head...

#include "SomeLibrary.h"

static_assert(SomeLibrary::Version > 2, 
         "Old versions of SomeLibrary are missing the foo functionality.  Cannot proceed!");

class UsingSomeLibrary {
   // ...
};

Assuming that SomeLibrary::Version is declared as a static const, rather than being #defined (as one would expect in a C++ library).

Contrast with having to actually compile SomeLibrary and your code, link everything, and run the executable only then to find out that you spent 30 minutes compiling an incompatible version of SomeLibrary.

@Arak, in response to your comment: yes, you can have static_assert just sitting out wherever, from the look of it:

class Foo
{
    public: 
        static const int bar = 3;
};

static_assert(Foo::bar > 4, "Foo::bar is too small :(");

int main()
{ 
    return Foo::bar;
}

$ g++ --std=c++0x a.cpp
a.cpp:7: error: static assertion failed: "Foo::bar is too small :("

这篇关于static_assert 有什么作用,你会用它做什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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