C++14 - constexpr

Variables delcared as constexpr need to be initialized i.e. their values are known at compile time and this allows these variables to be used further to intialize other objects. Example -

constexpr auto size = 100;

Variables delcared as const may not be intialized, thus their values would not be known and hence they can’t be used as constexpr variables can (as above).

Functions can be declared with constexpr if they are guaranteed to return the same value when invoked with constexpr parameters. Example -

constexpr int twice(int input)
{
  return 2 * input;
}

constexpr auto size = 100;
auto size2 = twice(size);

The fucntion twice will return a value which can be coputed at copmile time if the input value is also known at compile time. There are no runtime variations to the return value.

C++11 restricted constexpr functions to have only one stamement i.e. the return statement. It also restricts the return type to be anything but void. The single statement can be worked aorund by using recursion or the ternary operator  (?:).

C++14 does not have either of these restrictions. This allows class member functions to be declared constexpr. Meyers provides an example -

class Point {
  public:
    constexpr Point(double xval = 0, double yval = 0) : x(xval), y(yval) {}
    constexpr double xvalue() { return x; }
    constexpr void setx(double newx) { x = newx; }
//...
};

The ctor is guaranteed to create the same object if inputs are known at compile time. The xvalue and setx functions are also guaranteed to return or set the value of x. Thus these statements are evaluated at compile time -

constexpr Point p(10, 20);
p.setx(-1 * p.xvalue());