c++ - Function taking both pointer to member-function and pointer to const member-function -


i have 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 pass pointer member-function (non-const). however, if want pass pointer const member-function, results in compile error , must duplicate above function 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, can pass both const-member-functions , non-const-member-functions. but, now, code duplicate , maintainability reduced.

is there way merge these 2 functions function taking both const-member-functions , non-const-member-functions?

important note: must take pointer function parameter (no std::function).

edit: i've added little bit more code. inside functions, build closure matching member function signature (same return types , params). closure stored , used later making reflection (more here)

you write type trait, based on tell if mf pointer-to-member function on type:

template <typename c, typename t> struct is_pointer_to_member_helper : std::false_type { };  template <typename c, typename t> struct is_pointer_to_member_helper<c, t c::*> : std::is_function<t> { };  template <typename c, typename t> struct is_pointer_to_member : is_pointer_to_member_helper<c,                                   std::remove_cv_t<t>                               > { }; 

and use ensure 1 of those:

template <typename type> class someclass { public:     template <typename mf>     std::enable_if_t<is_pointer_to_member<type, mf>::value>     register_function(const std::pair<std::string, mf> fct)      {         auto f = [fct](auto&&... params) {             return (type{}.*fct.second)(std::forward<decltype(params)>(params)...);         };          // ...     } }; 

Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -