Can I research methods using Boost Hana?

Boost Hana provides the ability to introspect class fields in a simple and beautiful way:

// define: struct Person { std::string name; int age; }; // below could be done inline, but I prefer not polluting the // declaration of the struct BOOST_HANA_ADAPT_STRUCT(not_my_namespace::Person, name, age); // then: Person john{"John", 30}; hana::for_each(john, [](auto pair) { std::cout << hana::to<char const*>(hana::first(pair)) << ": " << hana::second(pair) << std::endl; }); 

However, only member fields are mentioned in the documentation. I would also like to learn the methods. I tried to naively extend the example using the method:

 struct Foo { std::string get_name() const { return "louis"; } }; BOOST_HANA_ADAPT_STRUCT(::Foo, get_name); 

It compiles. However, as soon as I try to use it using code similar to the above ( for_each ...), I get a lot of compilation errors. Since there are no examples that show introspection of methods, I wonder if it is supported.

+7
c ++ reflection generic-programming c ++ 14 boost-hana
source share
1 answer

My original answer was shit; sorry for that. It corresponded here that actually answers the question.

I just added a macro to easily define Struct with custom accessories. Here is how you could do it:

 #include <boost/hana/adapt_adt.hpp> #include <boost/hana/at_key.hpp> #include <boost/hana/string.hpp> #include <cassert> #include <string> namespace hana = boost::hana; struct Person { Person(std::string const& name, int age) : name_(name), age_(age) { } std::string const& get_name() const { return name_; } int get_age() const { return age_; } private: std::string name_; int age_; }; BOOST_HANA_ADAPT_ADT(Person, (name, [](auto const& p) { return p.get_name(); }), (age, [](auto const& p) { return p.get_age(); }) ); int main() { Person bob{"Bob", 30}; assert(hana::at_key(bob, BOOST_HANA_STRING("name")) == "Bob"); assert(hana::at_key(bob, BOOST_HANA_STRING("age")) == 30); } 

This code should work on master . Otherwise, if you need more control over the definition of your accessories or the keys used to match them, you can also define all of these manually:

 namespace boost { namespace hana { template <> struct accessors_impl<Person> { static auto apply() { return hana::make_tuple( hana::make_pair(BOOST_HANA_STRING("name"), [](auto&& p) -> std::string const& { return p.get_name(); }), hana::make_pair(BOOST_HANA_STRING("age"), [](auto&& p) { return p.get_age(); }) ); } }; }} 

You can find more information on how to define Struct in the link for the Struct concept.

+9
source share

All Articles