I cannot pass lambda as std::function(我不能将 lambda 作为 std::function 传递)
问题描述
让我们关注这个例子:
template<typename T>
class C{
public:
void func(std::vector<T>& vec, std::function<T( const std::string)>& f){
//Do Something
}
};
现在,我正在尝试:
std::vector<int> vec;
auto lambda = [](const std::string& s) { return std::stoi(s); };
C<int> c;
c.func(vec, lambda);
它会导致错误:
no matching function for call to ‘C<int>::func(std::vector<int, std::allocator<int> >&, main()::<lambda(const string&)>&)’
ref.parse(vec, lambda);
请向我解释什么是不好的,以及如何用 std::bind 实现它.
Please explain me what is not ok and how to implement it with std::bind as well.
推荐答案
这是因为 lambda 函数不是 std::function<...>.
It's because a lambda function is not a std::function<...>. The type of
auto lambda = [](const std::string& s) { return std::stoi(s); };
不是 std::function,而是可以分配给 std::function 的未指定的东西.现在,当您调用您的方法时,编译器会抱怨类型不匹配,因为转换意味着创建一个无法绑定到非常量引用的临时对象.
is not std::function<int(const std::string&)>, but something unspecified which can be assigned to a std::function. Now, when you call your method, the compiler complains that the types don't match, as conversion would mean to create a temporary which cannot bind to a non-const reference.
这也不是特定于 lambda 函数,因为当您传递普通函数时会发生错误.这也行不通:
This is also not specific to lambda functions as the error happens when you pass a normal function. This won't work either:
int f(std::string const&) {return 0;}
int main()
{
std::vector<int> vec;
C<int> c;
c.func(vec, f);
}
您可以将 lambda 分配给 std::function
You can either assign the lambda to a std::function
std::function<int(const std::string&)> lambda = [](const std::string& s) { return std::stoi(s); };
,更改您的成员函数以按值或常量引用获取函数或使函数参数成为模板类型.如果您传递 lambda 或普通函数指针,这会稍微高效一些,但我个人喜欢签名中富有表现力的 std::function 类型.
,change your member-function to take the function by value or const-reference or make the function parameter a template type. This will be slightly more efficient in case you pass a lambda or normal function pointer, but I personally like the expressive std::function type in the signature.
template<typename T>
class C{
public:
void func(std::vector<T>& vec, std::function<T( const std::string)> f){
//Do Something
}
// or
void func(std::vector<T>& vec, std::function<T( const std::string)> const& f){
//Do Something
}
// or
template<typename F> func(std::vector<T>& vec, F f){
//Do Something
}
};
这篇关于我不能将 lambda 作为 std::function 传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:我不能将 lambda 作为 std::function 传递
基础教程推荐
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
