调用包含可调用项和参数的元组

Bar*_*uch 2 c++ c++17

我试图以第二个参数作为参数调用元组中的第一个参数,但不知道如何执行。

例子:

#include <tuple>
#include <functional>

struct S {
    void operator()(int) {}
};

int main() {
    S s;
    auto t = std::make_tuple(s, 3);
    std::invoke(s, 3);
    // std::apply(std::invoke, t); // This is what I want to do
    // std::apply(std::invoke<S, int>, t); // I would settle for this "Good Enough"
}
Run Code Online (Sandbox Code Playgroud)

但上面的代码无法编译,并且该错误对我来说非常没有帮助:

错误:没有匹配的函数可调用 '__invoke(void (&)(S&&, int&&), std::__tuple_element_t<0, std::tuple<S, int> >&, std::__tuple_element_t<1, std::元组<S, int> >&)'

(这是来自“足够好”的尝试)

有谁知道如何做到这一点,或者是否无法做到?

Jar*_*d42 7

在 lambda 中包装重载/模板函数解决了很多问题:

std::apply([](auto&&... args){ std::invoke(args...); }, t);
Run Code Online (Sandbox Code Playgroud)

可能有转发:

std::invoke(std::forward<decltype(args)>(args)...);

否则,作为std::invoke模板函数(采用转发引用),您需要正确的类型:

std::apply(std::invoke<S&, int&>, t);
std::apply(std::invoke<S, int>, std::move(t));
Run Code Online (Sandbox Code Playgroud)

演示

关于错误读数:std::__tuple_element_t<0, std::tuple<S, int> >&S&,因此错误简化为

错误:没有匹配的函数可调用__invoke(void (&)(S&&, int&&), S&, int&)

您需要void (&)(S&, int&)(或传递S&&int&&作为函数的参数)