Итак, делегат это:
Код: Выделить всё
class Delegate
{
typedef void (*Type)(void* callee, int);
public:
Delegate(void* callee, Type function)
: fpCallee(callee)
, fpCallbackFunction(function) {}
template
static Delegate from_function(T* callee)
{
Delegate d(callee, &methodCaller);
return d;
}
void operator()(int x) const
{
return (*fpCallbackFunction)(fpCallee, x);
}
private:
void* fpCallee;
Type fpCallbackFunction;
template
static void methodCaller(void* callee, int x)
{
T* p = static_cast(callee);
return (p->*TMethod)(x);
}
};
Код: Выделить всё
class A
{
public:
void foo(int x)
{
printf("foo called with x=%d\n", x);
}
void bar(int x) {}
};
Код: Выделить всё
int main()
{
A a;
Delegate d = Delegate::from_function(&a);
d(42);
}
Итак, если у меня есть новая функция, которая принимает строку и печатает ее...
Код: Выделить всё
void printString(const std::string& str) {
std::cout
Подробнее здесь: [url]https://stackoverflow.com/questions/79206051/im-trying-to-implement-a-delegate-in-c-but-i-dont-understand-how-to-actuall[/url]
Мобильная версия