【发布时间】:2018-08-16 09:11:07
【问题描述】:
我正在学习 C++ 中的函数式编程。我的意图是传递一个非泛型函数作为参数。我知道模板方法,但是我想将函数签名限制为 API 设计的一部分。我想出了4种不同的方法example on cpp.sh:
// Example program
#include <iostream>
#include <string>
#include <functional>
typedef int(functor_type)(int);
int by_forwarding(functor_type &&x) {
return x(1);
}
int functor_by_value(functor_type x) {
return x(1);
}
int std_func_by_value(std::function<functor_type> x) {
return x(1);
}
int std_func_by_forwarding(std::function<functor_type> &&x) {
return x(1);
}
int main()
{
std::cout << functor_by_value([](int a){return a;}); // works
std::cout << std_func_by_value([](int a){return a;}); // works
std::cout << std_func_by_forwarding(std::move([](int a){return a;})); // works
//std::cout << by_forwarding([](int a){return a;}); // how to move lambda with forwarding ?
}
以上尝试是否正确?如果没有,我该如何实现我的目标?
【问题讨论】:
-
prog.cc:29:41: warning: moving a temporary object prevents copy elision:) 叮叮当当警告! -
简答:
int functor_by_value(functor_type x). -
std::invoke如果你可以访问 C++17 -
Lambda 是匿名的,所以只能通过类型推导来获取它的类型。
-
这取决于您放入“传递非通用函数”的含义前两个变体接受引用或指向函数的指针。第 3 和第 4 个变体接受对象或对具有重载
operator ()的对象的右值引用。所以每个x都有一个operator ()所以通常的调用语法x(1);可以工作,但是它们都不是函数。
标签: c++ function functor std-function