dimanche 30 janvier 2022

Call function pointers and member functions

I want to create a class which can take both normal function pointers but also member functions. Adding ot that it should take any return type and any type and amount of parameters. I've successfully created what i want by using std::async like this:

    template<class... _Args>
    std::result_of_t<_Fn&&(_Args&&...)> operator()(_Args&&... _Ax) {
        mutex.lock();

        //some extra stuff here

        auto task = std::async(std::launch::deferred, _function_data, std::forward<_Args>(_Ax)...);
        task.wait();

        //some more extra stuff here

        mutex.unlock();
        return task.get();
    }

usage:

    Wrapper<decltype(&TestFunction)> function(&TestFunction); //int TestFunction(int test_parameter)
    Wrapper<decltype(&MyClass::Test)> class_function(&MyClass::Test); //void MyClass::Test()
    class_function(&myClass);
    int test = function(10);

However this solution is obviously not optimal. How would i go about calling any type of function without having to use std::async?

Aucun commentaire:

Enregistrer un commentaire