在下面的代码中,我有一个名为data
的变量。它内部包含一个函数来稍后调用它们。假设data
在另一个库中定义,我无法更改其类型。我为其中每个已知函数的一部分(s3
)的成员分配模板函数,并且在调用函数时必须给出一部分函数(true
)。我能不能通过这样的事情:如何用已知的函数参数来避免lambda函数?
data[0]=test_func(?,s3); // error
相反,我要传递一个lambda函数给它:
data[0]=[](bool b){test_func(b,s3);}; // ok
但lambda函数看起来并不整齐尤其是当我们有100数组这些任务。有没有办法通过以任何方式更改test_func
来避免lambda函数?即使使用test_func
内的lambda也对我来说是可以的,因为它只写了一次。
#include <iostream>
#include <functional>
template<typename F>
void test_func(bool b,F f)
{
if(b)
f();
}
void s1()
{
std::cout<<"s1 \n";
}
void s2()
{
std::cout<<"s2 \n";
}
void s3()
{
std::cout<<"s3 \n";
}
int main()
{
test_func(true,s1);
test_func(true,s2);
test_func(false,s1);
test_func(true,s2);
/////////////////
std::function<void(bool)> data[100];
// data=test_func(?,s3); // error
data[0]=[](bool b){test_func(b,s3);}; // ok
data[0](true);
return 0;
}
这不只是'的std ::函数 foo(F f){return [](bool b){test_func(b,f); }; }'? –
melpomene
现在,最好的解决方案是简单地使用lambda函数。 'std :: bind'试图做到这一点,但使用它需要学习它的迷你语言(对于任何读取代码的人),并且往往会使编译器难以优化。此外,它最终只比lambda函数短。 – Justin
@melpomene,你如何适应这个代码? – ar2015