-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsquare.cc
39 lines (33 loc) · 856 Bytes
/
square.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
// Demonstrate `constexpr` for pure functions aka functions without side-effects.
#include <vector>
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include "doctest/doctest.h"
// square returns x^2 at runtime or compile-time.
constexpr double square(double x)
{
return x*x;
}
TEST_CASE("[square]")
{
struct test_case
{
double input;
double expected;
};
std::vector<test_case> test_cases{
{0.0, 0.0},
{1.0, 1.0},
{2.0, 4.0},
{3.0, 9.0}
};
for (const auto& c : test_cases) {
auto rcv = square(c.input);
CAPTURE(c.input);
CAPTURE(rcv);
CAPTURE(c.expected);
REQUIRE(rcv == doctest::Approx(c.expected));
}
// Compile-time expression.
constexpr double four_square = square(4.0);
REQUIRE(four_square == doctest::Approx(16.0));
}