Reputation: 11
I'm attempting to replace a series of static to non static member function pairs throughout my code, I can achieve this with a macro but I was hoping I could do so with a static function which takes the non static member function as a template argument, which then gets stored as a function pointer. See the following code:
struct widget_param
{
void* ptr;
};
struct widget_data
{
bool(*callback)(widget_param*);
};
template <class CLASSNAME>
class widget_base
{
protected:
static CLASSNAME* get_instance(widget_param* param)
{
return static_cast<CLASSNAME*>(param->ptr);
}
public:
template <bool(CLASSNAME::*f)(widget_param*)>
static bool static_to_nonstatic(widget_param* param)
{
return get_instance(param)->*f(param);
}
};
class widget_derived : public widget_base<widget_derived>
{
public:
// Attempting to replace this function
static bool static_do_stuff(widget_param* param)
{
return get_instance(param)->do_stuff(param);
}
bool do_stuff(widget_param* param)
{
param;
cout << "Success!";
return true;
}
};
int main() {
widget_derived derived;
//widget_data data{ widget_derived::static_do_stuff}; // Current approach
widget_data data{ widget_derived::static_to_nonstatic<widget_derived::do_stuff> };
widget_param param{ &derived };
data.callback(¶m);
return 0;
}
I was expecting the template to evaluate to:
static bool static_to_nonstatic(widget_param* param);
Is it possible to do what I'm trying to achieve, without resorting to using a macro?
Upvotes: 0
Views: 60
Reputation: 11
Resolved, since the call is to a member function pointer - it needed to be surrounded by parenthesis, changed the template to the following and it worked:
template <bool(CLASSNAME::*f)(widget_param*)>
static bool static_to_nonstatic(widget_param* param)
{
return (get_instance(param)->*f)(param);
}
Upvotes: 1