samedi 13 mai 2023

Correct template definition to wrap class member functions

I looked up to this and this SO answers, but none solves my problem.

Short description: the template function, where much more should happen than just that of this example, should be able to wrap any other function, also function members of a class.

Minimal working example:

#include <iostream>

template <typename T, typename ...ArgsT>
T wrapper(T(*func)(ArgsT...), ArgsT... args)
{
    return func(args...);
}

class TestClass
{
public:
    int mult_by_2_member(int a)
    {
        return a * 2;
    }

    static int mult_by_2_static(int a)
    {
        return a * 2;
    }

    void wrap_funcs()
    {
        // std::cout << "Wrapped member = " 
        //           << wrapper(&mult_by_2_member, 2)  // Prob: cannot convert `int(TestClass::*)(int) to int(*)(int)`
        //           << std::endl;
        std::cout << "Wrapped static = " << wrapper(mult_by_2_static, 2) << std::endl;
    }
};

int main()
{
    TestClass test_instance;
    test_instance.wrap_funcs();
    // skipping wrapping of a global function... that works correctly
}

The error message, as posted in the snippet above, is obvious. But I did not yet figure out how to solve it, or even whether the whole starting logic or intent is valid.

Any solution suggestions or sources of information?


EDIT

A possible solution would be:

/* as above */
static int mult_by_2_static(TestClass* p, int a)
{
   return p->mult_by_2_member(2);
}

void wrap_funcs()
{
    // std::cout << "Wrapped member = " << wrapper(&mult_by_2_member, 2) << " = " << std::endl;
    std::cout << "Wrapped static = " << wrapper(mult_by_2_static, this, 2) << std::endl;
}

But then I would have to "pre-wrap" all target member functions into static ones, which is a lot of boilerplate.

Aucun commentaire:

Enregistrer un commentaire