diff --git a/doc/describe/examples.adoc b/doc/describe/examples.adoc index 28faa07..91ab97e 100644 --- a/doc/describe/examples.adoc +++ b/doc/describe/examples.adoc @@ -161,6 +161,18 @@ using boost::describe::operators::operator==; The rest of the relational operators are also provided and can be enabled similarly. +[#example_struct_to_tuple] +## struct_to_tuple + +This example defines a function `struct_to_tuple` that takes +a described class type as an argument and returns a tuple of +all its public members. + +[source] +---- +include::../../example/struct_to_tuple.cpp[lines=5..-1] +---- + [#example_to_json] ## Automatic Conversion to JSON diff --git a/example/struct_to_tuple.cpp b/example/struct_to_tuple.cpp new file mode 100644 index 0000000..80eb8bb --- /dev/null +++ b/example/struct_to_tuple.cpp @@ -0,0 +1,55 @@ +// Copyright 2021 Peter Dimov +// Distributed under the Boost Software License, Version 1.0. +// https://www.boost.org/LICENSE_1_0.txt + +#include +#include + +namespace desc = boost::describe; + +template class L, class... D> +auto struct_to_tuple_impl( T const& t, L ) +{ + return std::make_tuple( t.*D::pointer... ); +} + +template> +auto struct_to_tuple( T const& t ) +{ + return struct_to_tuple_impl( t, Dm() ); +} + +#include +#include + +struct X +{ + int a = 1; +}; + +BOOST_DESCRIBE_STRUCT(X, (), (a)) + +struct Y +{ + float b = 3.14f; +}; + +BOOST_DESCRIBE_STRUCT(Y, (), (b)) + +struct Z: X, Y +{ +}; + +BOOST_DESCRIBE_STRUCT(Z, (X, Y), ()) + +int main() +{ + Z z; + + auto tp = struct_to_tuple( z ); + + std::cout << + boost::core::type_name() << ": " + << std::get<0>(tp) << ", " << std::get<1>(tp); +} diff --git a/test/Jamfile b/test/Jamfile index 742b169..72c2964 100644 --- a/test/Jamfile +++ b/test/Jamfile @@ -85,3 +85,4 @@ run ../example/json_rpc.cpp : : : $(CXX14) $(JSON) ; run ../example/hash_value.cpp : : : $(CXX14) ; run ../example/equality.cpp : : : $(CXX14) ; link ../example/console.cpp : $(CXX14) $(JSON) ; +run ../example/struct_to_tuple.cpp : : : $(CXX14) ;