一呼百應, "one call, a hundred responses"
Loading...
Searching...
No Matches
concepts.hpp
Go to the documentation of this file.
1#pragma once
2
29#include <concepts>
30
31#define ein_ensures(concept, x) \
32 ( \
33 []<typename T> static constexpr noexcept { \
34 static_assert(concept<T>, #concept " not satisfied"); \
35 }.template operator()<decltype(x)>(), \
36 (x) \
37 )
38
39#if defined(EIN_TESTING) || defined(EIN_TESTING_CONCEPTS)
40#include <string>
41
42// Sample functions using ein_ensures for test cases
43static auto add_integers(std::integral auto x, std::integral auto y) {
44 return ein_ensures(std::integral, x + y);
45}
46
47static auto add_floats(std::floating_point auto x, std::floating_point auto y) {
48 return ein_ensures(std::floating_point, x + y);
49}
50
51template <typename T>
52concept Stringifiable = requires(T a) {
53 { std::to_string(a) } -> std::convertible_to<std::string>;
54};
55
56static auto stringifyable_addition(Stringifiable auto x, Stringifiable auto y) {
57 return ein_ensures(Stringifiable, x + y);
58}
59
60TEST_CASE("concepts","[concepts]") {
61 SECTION("Test integral addition with ein_ensures") {
62 CHECK(add_integers(2, 3) == 5);
63 CHECK(add_integers(-10, 4) == -6);
64 }
65
66 SECTION("Test floating-point addition with ein_ensures") {
67 CHECK(add_floats(1.5, 2.0) == Catch::Approx(3.5));
68 CHECK(add_floats(-10.0, 4.5) == Catch::Approx(-5.5));
69 }
70
71 SECTION("Test custom concept Stringifiable with ein_ensures") {
72 CHECK(stringifyable_addition(10, 20) == 30);
73 }
74
75 SECTION("Test ein_ensures with non-matching concept should compile-time fail") {
76 // Intentionally left commented as examples of cases that should fail to compile
77 // REQUIRE(add_integers(2.5, 3.5) == 6.0); // Should fail on non-integral inputs
78 // REQUIRE(add_floats(1, 2) == 3); // Should fail on non-floating point inputs
79 }
80}
81#endif
#define ein_ensures(concept, x)
statically checks that a concept is satisfied by the type of an expression
Definition concepts.hpp:31