gpt4 book ai didi

c++ - 如何调用在另一个 stackoverflow 中找到的已创建仿函数对象?

转载 作者:行者123 更新时间:2023-11-28 05:45:24 24 4
gpt4 key购买 nike

在stackoverflow问题中Template function that can take lambda or function pointer and deduce arguments for passing to another template有一个通过 CreateFunctor 调用创建的仿函数对象。我如何使用它来调用 doSomething

int main(){
auto f1 = CreateFunctor([](int a, int b){doSomething(a, b);}, 1, 2);
f1(1,2);
}

不起作用。

参见 http://coliru.stacked-crooked.com/a/954b1f64fd13739e例如。

最佳答案

您引用的帖子中 CreateFunctor 的目的是创建一个函数对象,该对象在构造时将参数绑定(bind)到 lambda。

您在调用 CreateFunction 时执行此操作,但在调用函数对象时也再次传递参数。

因为参数已经绑定(bind),所以这是不必要的(实际上是不可能的)。

只需调用 f1()。

评论:引用的帖子旨在提高绑定(bind)函数对象的性能,超过 std::function 已经提供的性能。我怀疑作者过早地优化了。 Std::function 已经内置了性能优化。

编辑:在链接末尾找到代码

编译器错误信息非常明确:

./functor.cpp:57:5: error: type 'Functor<int, int>' does not provide a call operator

问题出在这里:

template<class... Args> struct Functor{
Functor(void (*)(Args...)) {std::cout << "Functor\n" << std::endl;}
void Set(Args...) {std::cout << "Set\n" << std::endl;}
};

Functor 模板类不完整。它没有定义调用操作符(根据错误消息)。

为什么不省去麻烦并使用标准对象呢?

auto f1 = std::function([] { do_something(1, 2); });
f1();

auto f1 = std::function([a = 1, b = 2]{ do_something(a,b); });

关于c++ - 如何调用在另一个 stackoverflow 中找到的已创建仿函数对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36327285/

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