静态模板化成员函数作为函数指针

时间:2016-03-06 14:17:41

标签: c++

我试图在我的代码中替换一系列静态到非静态成员函数对,我可以用宏来实现这一点,但我希望我能用静态函数来实现这一点,它将非静态成员函数作为模板参数,然后存储为函数指针。请参阅以下代码:

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;
}

我期待模板评估为:

static bool static_to_nonstatic(widget_param* param);

是否有可能做到我想要实现的目标,而无需使用宏?

1 个答案:

答案 0 :(得分:1)

已解决,因为调用是一个成员函数指针 - 它需要被括号括起来,将模板更改为以下内容并且它有效:

template <bool(CLASSNAME::*f)(widget_param*)>
static bool static_to_nonstatic(widget_param* param)
{
    return (get_instance(param)->*f)(param);
}