如何在 C++ 中将参数包传递给 void 指针?

Giz*_*zmo 3 c++ variadic-templates std-function

请考虑以下代码示例:

#include <functional>
#include <iostream>

template <typename... Ts>
class SomeClass
{
public:
    std::function<bool(Ts...)> some_func;

    void run(Ts... args)
    {
        this->some_func(args...); // this works

        this->thread_run((void *)&this->some_func, args); // this won't work, can't pass the parameter pack
    }

    static void thread_run(void *func_ptr, void *args_ptr)
    {
        auto thread_func = *(std::function<bool(Ts...)> *)(func_ptr);
        thread_func(2, 3);
    }
};

int main()
{
    SomeClass<int, int> a;

    a.some_func = [](int x, int y)
    { std::cout << "Arguments: " << x << " " << y << std::endl; return x > y; };

    a.run(2, 3);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,有一个类具有模板std::function成员变量。我可以通过给它一个必须返回bool但可以有任意数量的参数的 lambda 表达式来设置它,这很好!

遗憾的是,我现在面临的任务是使用给定的线程库(这是不可协商的)将这个函数作为线程运行。线程库的入口函数必须是static具有以下签名的函数:

void (*thread_entry_t)(void *p1, void *p2)

我已经设法将std::function变量传递给static示例中的函数,请参阅thread_run()函数,但我找不到通过指针将参数包传递args给函数的方法。staticvoid*

我怎样才能做到呢?

Cal*_*eth 5

您可以包装args...在一个元组中,并传递一个指向它的指针。我已使其成为您的类的成员,以便它与该std::function对象具有相同的生命周期。

template <typename... Ts>
class SomeClass
{
public:
    std::function<bool(Ts...)> some_func;
    std::tuple<Ts...> args;

    void run(Ts... args)
    {
        this->args = { args... };    
        thread_run((void *)&this->some_func, (void *)&this->args);
    }

    static void thread_run(void *func_ptr, void *args_ptr)
    {
        auto & thread_func = *(std::function<bool(Ts...)> *)(func_ptr);
        auto & args = *(std::tuple<Ts...> *)(args_ptr);
        std::apply(thread_func, args);
    }
};
Run Code Online (Sandbox Code Playgroud)