简体   繁体   English

调用 function 指针和成员函数

[英]Call function pointers and member functions

I want to create a class which can take both normal function pointers but also member functions.我想创建一个 class ,它既可以采用普通的 function 指针,也可以采用成员函数。 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:我已经通过使用 std::async 成功地创建了我想要的东西,如下所示:

    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?我将如何 go 调用任何类型的 function 而不必使用 std::async?

std::invoke was indeed the answer to my question although it needed a wrapper class to support calls to functions with return type 'void'. std::invoke 确实是我问题的答案,尽管它需要一个包装器 class 来支持对返回类型为“void”的函数的调用。 Here's the invoke wrapper i'm using and it's usage:这是我正在使用的调用包装器及其用法:

template<class t>
class invoke {
public:
    template<class c, class... Args>
    invoke(c&& f, Args&&... arg)
    {
        return_value = std::invoke(f, std::forward<Args>(arg)...);
    }
    t get() { return return_value; }
private:
    t return_value;
};
template<>
class invoke<void> {
public:
    template<class c, class... Args>
    invoke(c&& f, Args&&... arg)
    {
        std::invoke(f, std::forward<Args>(arg)...);
    }
    void get() { return; }
};
template<class... _Args, class return_type = std::result_of_t<_Fn && (_Args&&...)>>
return_type operator()(_Args&&... _Ax) {
    mutex.lock();

    auto return_value = invoke<return_type>(_function_data, std::forward<_Args>(_Ax)...);

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

This is needed since you cannot store a variable of type 'void' but you can return a function with return type of it.这是必需的,因为您无法存储“void”类型的变量,但您可以返回 function 及其返回类型。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM