在 C++ 中实现委托的选择数量之多令人难以置信。以下是我想到的。
选项 1:函子:
可以通过实现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);
选项 2:lambda 表达式(仅限C++11)
// Syntax is roughly: [capture](parameter list) -> return type {block}
// Some shortcuts exist
auto func = [](int i) -> double { return 2*i/1.15; };
double d = func(1);
选项 3:函数指针
int f(double d) { ... }
typedef int (*MyFuncT) (double d);
MyFuncT fp = &f;
int a = fp(3.14);
选项 4:指向成员函数的指针(最快的解决方案)
见Fast C++ Delegate(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);
选项 5:std::function
(或boost::function,如果您的标准库不支持它)。它速度较慢,但最灵活。
#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
选项 6:绑定(使用 std::bind)
允许提前设置一些参数,方便调用成员函数等实例。
struct MyClass
{
int DoStuff(double d); // actually a DoStuff(MyClass* this, double d)
};
std::function<int(double d)> f = std::bind(&MyClass::DoStuff, this, std::placeholders::_1);
// auto f = std::bind(...); in C++11
选项 7:模板
接受任何与参数列表匹配的内容。
template <class FunctionT>
int DoSomething(FunctionT func)
{
return func(3.14);
}