func 函数的嵌套 C delegate
- 给一个数n,如果能被3整除就print Func3(n),如果能被5整除就print Func5(n),如果能被3和5整除就print Func3(Func5(n)).
- follow-up, 把上面的代码改成general的,如这时有{3,5,7},能被3和7整除的话就print Func3(Func7(n)),能被3,5,7都整除print Func3(Func5(Func7(n)))
You have an incredible number of choices to achieve delegates in C++. Here are the ones that came to my mind.
Option 1 : functors:
A function object may be created by implementing operator()
struct Functor { // Normal class/struct members
int operator()(double d) // Arbitrary return types and parameter list
{
return (int) d + 1;
}
};
// Use: Functor f; int i = f(3.14);
Option 2: lambda expressions (C++11 only)
// Syntax is roughly: [capture] (parameter list) -> return type {block} // Some shortcuts exist auto func = -> double { return 2*i/1.15; }; double d = func(1);
Option 3: function pointers
int f(double d) { ... } typedef int (*MyFuncT) (double d); MyFuncT fp = &f; int a = fp(3.14);
Option 4: pointer to member functions (fastest solution)
See Fast C++ Delegate (on The Code Project).
struct DelegateList { int f1(double d) { } int f2(double d) { } };
typedef int (DelegateList::* DelegateType)(double d);
DelegateType d = &DelegateList::f1; DelegateList list; int a = (list.*d)(3.14);
Option 5: std::function
(or boost::function if your standard library doesn't support it). It is slower, but it is the most flexible.
#include <functional>
std::function<int(double)> f = [can be set to about anything in this answer]
// Usually more useful as a parameter to another functions
Option 6: binding
Allows setting some parameters in advance, convenient to call a member function for instance.
struct MyClass { int DoStuff(double d); // actually a DoStuff(MyClass* this, double d) };
std::function
Option 7: templates
Accept anything as long as it matches the argument list.
template