C++ template function for method with a parameter of a const type or simply of type -
assuming have same body 2 template functions calling class methods, these:
template <typename jstype, typename jsparamtype, typename paramprivatetype = jsparamtype::privatetype, void(privatetype::*method)(const paramprivatetype&)> static bool setbyrefmethod(jscontext *cx, unsigned argc, js::value *vp) { ... } template <typename jstype, typename jsparamtype, typename paramprivatetype = jsparamtype::privatetype, void(privatetype::*method)( paramprivatetype&)> static bool setbyrefmethod(jscontext *cx, unsigned argc, js::value *vp) { ... }
i try write once body, right way make compiler use when called method has parameter const
, when has parameter not const
?
you don't need template types. first do. if can deduce rest of types using first templated type should fine. don't need private types in template if can deduced first template type. check out following code
#include <iostream> using std::cout; using std::endl; #include <vector> using std::vector; class { public: using classtype = int; void print_const_integer(const int& a) { cout << "a's member function accepting const ref called" << endl; cout << << endl; } void print_integer(int& a) { cout << "a's member function accepting ref called" << endl; cout << << endl; } }; class b { public: using classtype = int; void print_integer(int& a) { cout << "b's member function called" << endl; cout << << endl; } }; template <typename type> void function(type object, void (type::*member_func_pointer)(int&)) { typename type::classtype = 1; (object.*member_func_pointer)(a); } template <typename type> void function(type object, void (type::*member_func_pointer)(const int&)) { typename type::classtype = 1; (object.*member_func_pointer)(a); } int main() { a; b b; function(a, &a::print_const_integer); function(a, &a::print_integer); function(b, &b::print_integer); return 0; }
hope helped!
Comments
Post a Comment