I have the following code base:
template <typename Type>
class SomeClass {
public:
template <typename ReturnType, typename... Params>
void register_function(const std::pair<std::string, ReturnType (Type::*)(Params...)> fct) {
auto f = [fct](Params... params) -> ReturnType { return (Type().*fct.second)(std::ref(params)...); }
// ...
}
};
This works when I pass a pointer to a member-function (non-const). However, if I want to pass a pointer to a const member-function, it results in a compile error and I must duplicate the above function to get this code:
template <typename Type>
class SomeClass {
public:
template <typename ReturnType, typename... Params>
void register_function(const std::pair<std::string, ReturnType (Type::*)(Params...)> fct) {
auto f = [fct](Params... params) -> ReturnType { return (Type().*fct.second)(std::ref(params)...); }
// ...
}
template <typename ReturnType, typename... Params>
void register_function(const std::pair<std::string, ReturnType (Type::*)(Params...) const> fct) {
auto f = [fct](Params... params) -> ReturnType { return (Type().*fct.second)(std::ref(params)...); }
// ...
}
};
Now, I can pass both const-member-functions and non-const-member-functions. But, now, the code is duplicate and maintainability is reduced.
Is there a way to merge these two functions into a function taking both const-member-functions and non-const-member-functions?
Important note: I must really take a pointer function as parameter (no std::function).
Edit: I've added a little bit more code. Inside the functions, I build a closure matching the member function signature (same return types and params). This closure will be stored and used later for making reflection (more here)
template<typename Fun> void register_function(Fun fct)
? – fredoverflow