Skip to content

Instantly share code, notes, and snippets.

@Cylix
Created October 19, 2020 05:48
Show Gist options
  • Save Cylix/8d1223d5f4af8cf35aa7814eb6308d4b to your computer and use it in GitHub Desktop.
Save Cylix/8d1223d5f4af8cf35aa7814eb6308d4b to your computer and use it in GitHub Desktop.
Reflection in C++14 - Member Function #3
template <typename Type>
class reflectable : reflectable_base {
public:
//! constructor of a reflectable class where we can process the registration
//! note the presence of variadic template to accept any number of member functions
template <typename... Fcts>
reflectable(const std::string& class_name, Fcts... fcts) : name(class_name) {
reflection_manager::get_instance().register_reflectable(*this);
register_function(fcts...);
}
//! iterate over the parameters pack
template <typename Head, typename... Tail>
void register_function(const Head& head, Tail... tail) {
register_function(head);
register_function(tail...);
}
//! register specific member function
template <typename ReturnType, typename... Params>
void register_function(const std::pair<std::string, ReturnType (Type::*)(Params...)>& f) {
//! wrap the instanciation of a new object of type Type and the call to the function f in a C++11 lambda
auto f_wrapper = [f](Params... params) -> ReturnType {
return (Type().*f.second)(params...);
};
//! store function information
functions.push_back({
f.first, //! function name
std::make_shared<function<ReturnType(Params...)>>(f_wrapper) //! function object
});
}
//! member functions getter
const std::vector<std::pair<std::string, std::shared_ptr<function_base>>>& get_functions(void) const {
return this->functions;
}
//! function to get reflectable name
const std::string& get_name(void) const {
return this->name;
}
private:
std::string name;
std::vector<std::pair<std::string, std::shared_ptr<function_base>>> functions;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment