У вас есть невероятное количество вариантов для достижения делегатов в 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: лямбда-выражения (только 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 (в проекте кода ).
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);
}