gpt4 book ai didi

c++ - 使用扩展元组参数调用成员函数 std::invoke 与 std::apply

转载 作者:太空狗 更新时间:2023-10-29 23:24:34 25 4
gpt4 key购买 nike

我找到了 std::invoke使用一组参数和 std::apply 调用每个可调用对象将元组作为参数扩展到可调用对象。

是否有两者的组合可以调用任何带有元组作为参数的可调用对象?

#include <iostream>
#include <tuple>
#include <functional>

class A
{
private:
int n;

public:
A( int _n ): n(_n){}

void operator()(int x, double y )
{
std::cout << n << " " << x << " " << y << std::endl;
}

void MemFun( int x, double y )
{
std::cout << n << " " << x << " " << y << std::endl;
}
};

int main()
{
A a(100);
std::invoke( a, 10, 1.23 );

auto parm2 = std::make_tuple( 1,2.34);
std::apply ( a, parm2 );

std::invoke ( &A::MemFun, a, 4, 5.67 );

// ???
std::??apply_invoke?? ( &A::MemFun, a, parm2 );
}

最佳答案

你的意思是这样的吗?

std::apply(&A::MemFun, std::tuple_cat(std::make_tuple(a), parm2));

Is there a combination of both which enables to invoke any callable with a tuple as parms?

std::apply可以用来调用任何可调用对象,所以我不太了解这里的问题。就像成员函数的 std::invoke 一样:第一个参数需要是您要对其调用函数的对象。 std::apply 也是如此,其中传递的元组的第一个元素需要是您希望调用它的对象。

如果您不喜欢指定 std::tuple_cat 等,您始终可以创建一个包装器:

template<typename F, typename T, typename U>
decltype(auto) apply_invoke(F&& func, T&& first, U&& tuple) {
return std::apply(std::forward<F>(func), std::tuple_cat(std::forward_as_tuple(std::forward<T>(first)), std::forward<U>(tuple)));
}

关于c++ - 使用扩展元组参数调用成员函数 std::invoke 与 std::apply,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44776927/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com