C ++中的static_assert
static_assert是一个函数,对于程序员在编译程序后将错误打印在屏幕上而不会过多地干扰输出很有用。
在C++11和C++14的早期版本中,static_assert具有不同的功能,这意味着我们必须在定义static_assert的同时编写自己的消息。但是,在C++17中,可以在不传递消息的情况下调用static_assert。
它也与其他断言库函数(例如BOOST_STATIC_ASSERT)兼容。
语法
{
auto __range= For-range-Intializer;
auto __begin= begin-expression;
auto __end= end-expression;
for(; __begin!= __end; ++__begin){
range-declaration= *__begin;
statement
}
}__begin和__end的类型将有所不同;只需要比较运算符。该更改对现有的for循环没有影响,但为库提供了更多选项。例如,此小小的更改允许范围TS(和C++20中的范围)与基于范围的for循环一起使用。
在C++11中基于范围的for 循环-
for (for-range-declaration : for-range-initializer){
statement;
}在C++14标准中,这样的循环表达式等效于以下代码-
{
auto __range = for-initializer;
for ( auto __begin= begin-expresson, __end = end-expression; __begin != __end; ++__begin ){
for-range-declaration = *__begin;
statement
}
}示例
#include <bits/stdc++.h>
using namespace std;
template <typename T, size_t n, typename F> //模板声明
void fillarray (array<T, N> & a, F && f) //存储值的功能{
static_assert(is_convertible<typename result_of<F()>::type, T>::value,"Incompatible type returned by fun()"); //static_assert签名可忽略错误。
for (auto x : a)
x = f();
}
int main (){
array<vector<string>, 20> a;
fillarray(a, []() { return vector<string>{"nhooo"}; });
return 0;
}输出结果… … … prog.cpp:20:61: required from here prog.cpp:10:5: error: static assertion failed: Incompatible type returned by fun()