veselink1 / refl-cpp

Static reflection for C++17 (compile-time enumeration, attributes, proxies, overloads, template functions, metaprogramming).
https://veselink1.github.io/refl-cpp/md__introduction.html
MIT License
1.04k stars 75 forks source link

How to resolve the non-const signature of a class method. #81

Open rpatters1 opened 1 year ago

rpatters1 commented 1 year ago

Suppose I have this class:

class Foo
{
   const char* getPtr();
   char* getPtr();
}

REFL_AUTO(type(Foo), func(getPtr))

I would like write my code always to resolve the non-const version of the function, if there is an overload.

EDIT:

I was able to get resolve to work by looking at some of the tests for an example. (I think the documentation could be clearer.) My challenge is that it required hard-coding the function call signature with which to resolve it. I am processing many classes each with many functions in a centralized function. I would like somehow to pass in the calling sequences for the members that need resolution. It almost certainly would have to be in the REFL_AUTO macro. The question is how. At the moment I am stumped.

What would be ideas is if there were exactly 2 versions of the method, one const and one non-const, refl-cpp offered a way to resolve to the non-const without my code having to know the function signature.

rpatters1 commented 1 year ago

Would it be possible to add a version of REFL_FUNC that takes a function pointer? That seems like the most efficient way to handle overloads. Usage would look something like:

REFL_FUNC_PTR(MyMethod, static_cast<const char*(*)(int, bool)>(&MyClass::MyMethod))
rpatters1 commented 1 year ago

EDIT: Success! It works with refl::descriptor::get_attribute<func_ptr>. The code as modified below works.


template <typename Func>
struct func_ptr : refl::attr::usage::member
{
   Func func;
   constexpr func_ptr(Func func) : func(func) {}

};

REFL_AUTO(type(Foo), func(getPtr, func_ptr(static_cast<char*(foo::*)()>(&getPtr))))

// and in the central handler routine:

   constexpr auto type = refl::reflect<tinyxml2::XMLNode>();
   constexpr auto members = get_members(type);
   for_each_unordered(members, [&](auto member)
   {
      if constexpr(refl::descriptor::has_attribute<func_ptr>(member))
      {
         const auto fptr = refl::descriptor::get_attribute<func_ptr>(member).func;
      }
      else
      {
         const auto fptr = refl::descriptor::get_pointer(member);
      }
   });

It also works if you want to use a proxy function instead of the class member. Unfortunately the REFL_FUNC macro does not appear to be compatible with lambdas or std::function, but that's a small quibble.