C++中委托的一般概念是什么?它们是什么,它们如何使用以及它们用于什么?
我想首先以"黑匣子"的方式了解它们,但是关于这些事情的内容的一些信息也会很棒.
这不是最纯粹或最干净的C++,但我注意到我工作的代码库有很多.我希望能够理解它们,所以我可以使用它们,而不必深入研究可怕的嵌套模板.
这两个代码项目文章解释了我的意思,但不是特别简洁:
我尝试创建一个当前类的成员函数指针数组,但暂时没有成功...
我已经尝试了很多东西,这是我的代码:
// Human.hpp
#include <iostream>
class Human
{
private:
void meleeAttack(std::string const & target);
void rangedAttack(std::string const & target);
void intimidatingShout(std::string const & target);
public:
void action(std::string const & action_name, std::string const & target);
};
Run Code Online (Sandbox Code Playgroud)
// Human.cpp
#include "Human.hpp"
// ...
void Human::action(std::string const & action_name, std::string const & target)
{
std::string actionsStr[] = {"meleeAttack", "rangedAttack", "intimidatingShout"};
typedef void (Human::*Actions)(std::string const & target);
Actions actions[3] = {&Human::meleeAttack, &Human::rangedAttack, &Human::intimidatingShout};
for (int i = 2; i >= 0; i--)
if …Run Code Online (Sandbox Code Playgroud) 我需要遍历大量(2D)数据,并且仅有时处理特殊情况。对于我的应用程序来说,速度是最关键的因素。
(我)很快想到的选择是:
选项A:
void ifInLoop(bool specialCase, MyClass &acc) {
for (auto i = 0; i < n; ++i) {
for (auto j = 0; j < n; ++j) {
if (specialCase) {
acc.foo();
} else {
acc.bar();
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
选项B:
void loopsInIf(bool specialCase, MyClass &acc) {
if (specialCase) {
for (auto i = 0; i < n; ++i) {
for (auto j = 0; j < n; ++j) {
acc.foo();
}
}
} else { …Run Code Online (Sandbox Code Playgroud)