I was trying to get "more fluent" with function pointer manipulation and I've got an issue with passing a member function to std::function when there are two overload: const and non-const. Based on other stackoverflow posts, I eventually succeeded, using static_cast but it's all but readable.
Here is a dummy working example. The core of the issue is wrapping two member-function overloads (const and non-const):
#include <functional>
struct dummy {
int val = 42;
int get() const { return val; }
int& get() { return val; }
};
int main() {
dummy obj;
// std::function<int& (dummy &)> f = &dummy::get;
// std::function<int (dummy const &)> f = &dummy::get;
std::function<int&(dummy&)> f = static_cast<int& (dummy::*)()>(&dummy::get);
std::function<int(dummy const&)> fc =
static_cast<int (dummy::*)() const>(&dummy::get);
// just to check that it works as expected
f(obj) = 36;
return fc(obj); // ok retrives 36
}
Live
Is there a simpler syntax?
getmethods that way.auto f = [&obj]() -> int& { return obj.get(); };andauto fc = [&obj = std::as_const(obj)]() { return obj.get(); };