问题描述
让我们关注这个例子:
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 传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!