什么是 C++ 委托?

2022-01-18 00:00:00 delegation delegates c++

C++ 中委托的一般概念是什么?它们是什么,它们是如何使用的以及它们的用途是什么?

What is the general idea of a delegate in C++? What are they, how are they used and what are they used for?

我想首先以黑匣子"的方式了解它们,但了解一些关于这些东西的内脏的信息也很棒.

I'd like to first learn about them in a 'black box' way, but a bit of information on the guts of these things would be great too.

这不是最纯粹或最干净的 C++,但我注意到我工作的代码库有很多.我希望对它们有足够的了解,所以我可以直接使用它们,而不必深入研究可怕的嵌套模板的可怕之处.

This is not C++ at its purest or cleanest, but I notice that the codebase where I work has them in abundance. I'm hoping to understand them enough, so I can just use them and not have to delve into the horrible nested template awfulness.

这两篇代码项目文章解释了我的意思,但不是特别简洁:

These two The Code Project articles explain what I mean but not particularly succinctly:

  • 成员函数指针和最快的可能C++ 代表

不可能的快速 C++ 代表

推荐答案

在 C++ 中实现委托有很多选择.以下是我想到的.

You have an incredible number of choices to achieve delegates in C++. Here are the ones that came to my mind.

选项 1:函子:

一个函数对象可以通过实现operator()

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);

<小时>

选项 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++ 委托 (代码项目).

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).它速度较慢,但??最灵活.

(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

<小时>

选项 6:绑定(使用 std::bind)

允许提前设置一些参数,方便调用成员函数等实例.

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<int(double d)> f = std::bind(&MyClass::DoStuff, this, std::placeholders::_1);
// auto f = std::bind(...); in C++11

<小时>

选项 7:模板

接受任何与参数列表匹配的内容.

Accept anything as long as it matches the argument list.

template <class FunctionT>
int DoSomething(FunctionT func)
{
    return func(3.14);
}

相关文章