Skip to content

Instantly share code, notes, and snippets.

@jonwis
Created October 23, 2022 04:30
Show Gist options
  • Save jonwis/e64cf78550bbef3ea8ac06d8da509cb0 to your computer and use it in GitHub Desktop.
Save jonwis/e64cf78550bbef3ea8ac06d8da509cb0 to your computer and use it in GitHub Desktop.
Func or field
// Tool to either invoke a method or read a field on a type.
class MyTypeName {
using TSelf = MyTypeName;
template<typename T> using func_or_field = std::variant<
T(TSelf::*)(),
T TSelf::*>;
template<typename T> auto invoke_func_or_field(func_or_field<T> const& fof)
{
if (std::holds_alternative<T(TSelf::*)()>(fof))
{
return (this->*std::get<T(TSelf::*)()>(fof))();
}
else
{
return this->*std::get<T TSelf::*>(fof);
}
}
int _f1;
int _f2;
int Func1();
int Func2();
void use(int);
void calls() {
constexpr static const func_or_field<int> c[] = { &TSelf::_f1, &TSelf::_f2, &TSelf::_f3, &TSelf::_f4 };
for (auto&& i : c) {
use(invoke_func_or_field(i));
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment