gpt4 book ai didi

c++ - 延迟函数调用中的延迟函数调用

转载 作者:搜寻专家 更新时间:2023-10-31 01:05:52 24 4
gpt4 key购买 nike

基本上我想做的是:

std::function< int( void ) > foo = &getInt;
int magicNumber = 13;
std::function< int( void ) > delayedAdd = std::bind( std::plus, magicNumber, getInt );

显然这行不通。我需要以某种方式包装 getInt call 以便它在 std::plus 函数发生之前发生。然后所有这些都需要延迟,直到我调用 delayedAdd

我在 QObject 之外使用 Qt5.0,所以我无法将 lambda connectSLOT。但我想将 connect 之类的 delayedAdd 改为 SLOT

+标签功能

最佳答案

您可以使用 std::bind 延迟函数调用:

using namespace std;

int getInt() {
cout << "getInt!" << endl;
return 42;
}

function<int(void)> foo = &getInt;
int magicNumber = 13;

cout << "before delayed definition" << endl;
function<int(void)> delayed = std::bind(plus<int>(), magicNumber, bind(foo));
cout << "after delayed definition" << endl;

int i = delayed();

cout << "after delayed call" << endl;

输出:

before delayed definition
after delayed definition
getInt!
after delayed call

您也不需要像以前那样定义 foo。您可以直接在 delayed 的定义中绑定(bind) getInt:

function<int(void)> delayed = bind(plus<int>(), magicNumber, bind(getInt));

有关 std::bind 的更多详细信息,请查看 N3797 ,第 20.9.9 段。
如需更具体的解释,cppreference说:

std::bind return type
...
Member function operator() Given an object g obtained from an earlier call to bind, when it is invoked in a function call expression g(u1, u2, ... uM), an invocation of the stored object of type std::decay::type takes place, with arguments defined as follows:
...
- If std::is_bind_expression::value == true (i.e. another bind subexpression was used as an argument in the initial call to bind), then that bind subexpression is invoked immediately and its result is passed to the invocable object. If the bind subexpression has any placeholder arguments, they are picked from u1, u2, ....
...

关于c++ - 延迟函数调用中的延迟函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21911882/

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