static_assert in C++


static_assert is a function which is useful for programmers to print the error in the screen after compiling the program without messing up with the output too much.

Earlier in C++11 and C++14, static_assert had different functionality which means we have to write our own message while defining the static_assert. However, In C++ 17 static_assert can be invoked without passing the message.

It is compatible with other asserts libraries functions like BOOST_STATIC_ASSERT as well.

Syntax

{
   auto __range= For-range-Intializer;
   auto __begin= begin-expression;
   auto __end= end-expression;
   for(; __begin!= __end; ++__begin){
      range-declaration= *__begin;
      statement
   }
}

Types of __begin and __end will be different; only the comparison operator is required. That change has no effect on existing for loops but it provides more options for libraries. For example, this little change allows range TS (and ranges in C++20) to work with the range-based for loop.

In C++11 range-based for loops −

for (for-range-declaration : for-range-initializer){
   statement;
}

In C++14 standard, such loops expression was equivalent to the following code −

{
   auto __range = for-initializer;
   for ( auto __begin= begin-expresson, __end = end-expression; __begin != __end; ++__begin ){
      for-range-declaration = *__begin;
         statement
   }
}

Example

#include <bits/stdc++.h>
using namespace std;
template <typename T, size_t n, typename F> //Template Declaration
void fillarray (array<T, N> & a, F && f) //Function to store the values{
   static_assert(is_convertible<typename result_of<F()>::type, T>::value,"Incompatible type returned by fun()"); //static_assert signature to ommit the errors.
   for (auto x : a)
      x = f();
}
int main (){
   array<vector<string>, 20> a;
   fillarray(a, []() { return vector<string>{"TutorialsPoint"}; });
   return 0;
}

Output

…
…
…
prog.cpp:20:61: required from here
prog.cpp:10:5: error: static assertion failed:
Incompatible type returned by fun()

Updated on: 05-Feb-2021

259 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements