Skip to content

Commit 6c0facb

Browse files
committed
Add nested structure case
1 parent 7ad36d4 commit 6c0facb

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

include/reflection-cpp/reflection.hpp

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -361,6 +361,9 @@ namespace detail
361361
(f.template operator()<Xs>(), ...);
362362
}
363363

364+
template <typename T>
365+
constexpr bool can_be_formatted = std::is_arithmetic_v<T> || std::is_convertible_v<T, std::string>;
366+
364367
} // namespace detail
365368

366369
template <auto B, auto E, typename F>
@@ -433,9 +436,17 @@ std::string Inspect(Object const& object)
433436
if constexpr (std::is_convertible_v<T, std::string>
434437
|| std::is_convertible_v<T, std::string_view>
435438
|| std::is_convertible_v<T, char const*>) // clang-format on
439+
{
436440
str += std::format("\"{}\"", arg);
437-
else
441+
}
442+
else if constexpr (std::is_convertible_v<T, int>) // use std::formattable when available
443+
{
438444
str += std::format("{}", arg);
445+
}
446+
else
447+
{
448+
str += Inspect(arg);
449+
}
439450
};
440451
if (!str.empty())
441452
str += ' ';

test-reflection-cpp.cpp

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
#include <catch2/catch_test_macros.hpp>
55

6+
#include <iostream>
67
#include <string>
78
#include <string_view>
89

@@ -13,6 +14,15 @@ struct Person
1314
int age;
1415
};
1516

17+
struct TestStruct
18+
{
19+
int a;
20+
float b;
21+
double c;
22+
std::string d;
23+
Person e;
24+
};
25+
1626
enum Color
1727
{
1828
Red,
@@ -39,3 +49,10 @@ TEST_CASE("core", "[reflection]")
3949
auto const result = Reflection::Inspect(p);
4050
CHECK(result == R"(name="John Doe" email="[email protected]" age=42)");
4151
}
52+
53+
TEST_CASE("nested", "[reflection]")
54+
{
55+
auto ts = TestStruct { 1, 2.0f, 3.0, "hello", { "John Doe", "[email protected]", 42 } };
56+
auto const result = Reflection::Inspect(ts);
57+
CHECK(result == R"(a=1 b=2 c=3 d="hello" e=name="John Doe" email="[email protected]" age=42)");
58+
}

0 commit comments

Comments
 (0)