0

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(&param);
    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?

3
  • This just can't work. You need to store the this pointer somewhere, you can't solve it like this, at compile time. If you don't have C++ <functional>, probably you should just store a this pointer in struct widget_param Commented Mar 6, 2016 at 14:30
  • It works, see my answer Commented Mar 6, 2016 at 14:36
  • I see, I misunderstood the code. Or was too lazy to fully read it, sry. So param->ptr stores the this pointer. Commented Mar 6, 2016 at 14:52

1 Answer 1

1

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);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.