Static Assertions - C++ Data Type

C++ examples for Data Type:static_assert

Introduction

Static assertions are for checking conditions at compile time.

A static assertion is a statement of the form:

static_assert(constant_expression, error_message);

static_assert is a keyword.

constant_expression must produce a result at compile time that can be converted to type bool.

error_message is a string literal that is output as an error message by the compiler when constant_expression is false.

When constant_expression is true, the statement does nothing.

Demo Code

#include <type_traits>
#include <vector>
#include <iostream>
#include <string>

template<class T>
T average(const std::vector<T>& values) {
  static_assert(std::is_arithmetic<T>::value,
                          "Type parameter for average() must be arithmetic.");
  T sum {};/*from   ww w .  j  a  v  a  2 s  . c om*/
  for(auto& value : values)
    sum += value;
  return sum/values.size();
}

int main()
{
   std::vector<double> data {1.5, 2.5, 3.5, 4.5};
   std::cout << "The average of data values is " << average(data) << std::endl;

   //   std::vector<std::string> words {"this", "that", "them", "those"};
   //   std::cout << "The average of words values is " << average(words) << std::endl;
}

Result


Related Tutorials