Skip to Content
C++ High Performance
book

C++ High Performance

by Viktor Sehr, Björn Andrist
January 2018
Intermediate to advanced
374 pages
9h 53m
English
Packt Publishing
Content preview from C++ High Performance

Using static_assert to trigger errors at compile time

If we do the same to the template version, we can utilize static_assert(). The static_assert() declaration, unlike a regular assert, will refuse to compile if the condition isn't fulfilled. So, it's better to break the build than to break at runtime. In the following example, if the template parameter N is a negative number, static_assert() will prevent the function from compiling:

template <typename T, int N> 
auto const_pow_n(const T& v) { 
  static_assert(N >= 0, "N must be positive"); 
  auto product = T{1}; 
  for(int i = 0; i < N; ++i) { 
    product *= v; 
  } 
  return product; 
} auto x = const_pow_n<5>(2); // Compiles, N is positiveauto y = const_pow_n<-1>(2); // Does not compile, N is negative
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

C++ High Performance - Second Edition

C++ High Performance - Second Edition

Björn Andrist, Viktor Sehr
Advanced C++

Advanced C++

Gazihan Alankus, Olena Lizina, Rakesh Mane, Vivek Nagarajan, Brian Price
C++ In a Nutshell

C++ In a Nutshell

Ray Lischner
C++ Cookbook

C++ Cookbook

D. Ryan Stephens, Christopher Diggins, Jonathan Turkanis, Jeff Cogswell

Publisher Resources

ISBN: 9781787120952Supplemental Content