0
votes

I have a little class for callback with parameter

template<typename Ret, typename ...Args>
class Callback
{
public:
    typedef Ret (*Ptr)(Args..., void* param);
    Ptr m_func;
    void* m_param;
    void setFunc(void* func) { m_func = (Ptr)func; }
    template<typename T>
    void setFunc(const T& func) { m_func = (Ptr)func; }
};

"param" member is a void pointer, but it actually may point to different structs even in context of one callback So I can use setFunc with simple function like this:

void func1(..., ExampleContext* param) { ... }
callback.setFunc(func1);

But with non-capturing lambda I can only use it with strict void type:

callback.setFunc([](..., void* param) { ... });

I can convert lambda to its pointer, but I should write its typedef and cast, while I want setFunc to accept lambdas with any param type without additional conversions outside of Callback class, can I do it somehow? Thank you.

1
Why isn't func and param both std::function<Ret(Args...)>? The user can pass custom callback data with std::bind. - KamilCuk
I can't use std::function, because it's too heavy... - Quantum
This is all UB. You can cast a function pointer, but you must cast it back before calling. In your class, you lose the original type, so you have nothing to cast back to. - Raymond Chen

1 Answers

0
votes

I believe something like this should work:

template<typename Ret, typename Param = void, typename ...Args>
class Callback
{
public:
    template<typename T = Param>
    using Ptr = Ret (*)(Args..., T *param);
    Ptr<> m_func;
    Param *m_param;
    template<typename T = Param>
    void setFunc(Ptr<T> func) { m_func = (Ptr<>)func; }
};

Working copy:https://ideone.com/amapu0

However, you should be aware that using m_func without casting it back to the correct type is UB. While it is possible to do what you asked, this type of casting and dependence on UB is generally a sign that your code needs to be refactored. This is probably an x-y problem. To get a more appropriate solution, you'll have to explain WHY you want the m_param in a single instance of Callback to point to different types.