aCu*_*ria 16 c++ visual-studio-2010
基本上我想这样做: 我可以使用lambda函数或std :: function对象代替函数指针吗?
显然,对于期望函数指针的函数来说,现在是不可能的.但是,它适用于需要仿函数的函数(我之前使用过stl的sort()函数)
但是,我不知道如何编写一个以仿函数为参数的函数!
任何人?
Pet*_*der 19
只需编写一个任意类型的函数:
template <typename Func>
void foo(Func fun)
{
fun(...);
}
Run Code Online (Sandbox Code Playgroud)
然后,这将与函数指针,仿函数和lambda一起使用.
void f() {}
struct G
{
void operator()() {}
};
foo(&f); // function pointer
foo(G()); // functor
foo([]() { ... }); // lambda
Run Code Online (Sandbox Code Playgroud)
fre*_*low 17
我不知道如何编写一个以仿函数为参数的函数!
由于还没有人发布std::function解决方案:
#include <functional>
#include <iostream>
void foo(std::function<int(int)> f)
{
for (int i = 0; i < 10; ++i)
{
std::cout << f(i) << ' ';
}
std::cout << '\n';
}
int main()
{
foo( [](int x) { return x*x; } );
}
Run Code Online (Sandbox Code Playgroud)
您可以boost::function在pre C++ 11编译器中使用.
它必须是一个模板,如:
template<class F>
void foo( const F& f )
{
f(x,y);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10304 次 |
| 最近记录: |