constexpr

Basic Usage: Expressions

  • Requesting i to be calculated by compiler

  • ⟶ Input to calculation has to constexpr just as well

#include <gtest/gtest.h>

TEST(constexpr_suite, basic)
{
    constexpr int a = 10;
    constexpr int i = a*2;
    ASSERT_EQ(i, 20);
}
  • const is constexpr, clearly

#include <gtest/gtest.h>

TEST(constexpr_suite, basic_const_is_constexpr)
{
    const int a = 10;
    constexpr int i = a*2;
    ASSERT_EQ(i, 20);
}

constexpr Functions

  • Must be able, given only constexpr inputs, to be evaluated at compile time

  • ⟶ Can in turn only use constexpr functions

#include <gtest/gtest.h>

constexpr int multiply(int a, int b)
{
    return a*b;
}

TEST(constexpr_suite, constexpr_function_requested)
{
    constexpr int result = multiply(10, 20);
    ASSERT_EQ(result, 200);
}
  • constexpr function can be used with non-const inputs

  • ⟶ not done at compile time

  • ⟶ cannot request constexpr calculation

#include <gtest/gtest.h>

constexpr int multiply(int a, int b)
{
    return a*b;
}

// constexpr functions can be used when constexpr not requested
TEST(constexpr_suite, constexpr_function_not_requested)
{
    int a = 10, b = 20;
    int result = multiply(a, b);
    ASSERT_EQ(result, 200);
}

Recursive constexpr

#include <gtest/gtest.h>

constexpr int fibonacci(int n)
{
    if (n <= 1)
        return n;
    else
        return fibonacci(n-1) + fibonacci(n-2);
}

// constexpr request can be recursive
TEST(constexpr_suite, constexpr_recursive_function)
{
    constexpr int f = fibonacci(20);
    ASSERT_EQ(f, 6765);
}

constexpr Objects

#include <gtest/gtest.h>


// constexpr ctor

#include <cmath>

class point
{
public:
    constexpr point(int x, int y) : _x(x), _y(y) {}
    constexpr double abs() const
    {
        return std::sqrt(_x*_x + _y*_y);
    }
private:
    int _x;
    int _y;
};

TEST(constexpr_suite, constexpr_ctor)
{
    constexpr point p(3,4);
    ASSERT_FLOAT_EQ(p.abs(), 5);
}