在运行时向对象添加函数集合

Adding a collection of functions to an object at runtime

本文关键字:函数 集合 添加 对象 运行时      更新时间:2023-10-16

我想做的是在我的代码中实现角色编程技术。我正在使用C++。C++11很好。

我需要的是能够定义函数的集合。此集合不能具有状态。

此集合具有的某些功能将被推迟/委派。

例如(仅供参考:)

class ACCOUNT {
  int balance = 100;
  void withdraw(int amount) { balance -= amount; }
}
ACCOUNT savings_account;
class SOURCEACCOUNT {
  void withdraw(int amount); // Deferred.
  void deposit_wages() { this->withdraw(10); }
  void change_pin() { this->deposit_wages(); }
}
SOURCEACCOUNT *s;
s = savings_account; 
// s is actually the savings_account obj,
// But i can call SOURCEACCOUNT methods.
s->withdraw(...);
s->deposit();
s->change_pin();

我不想将 SOURCEACCOUNT 作为 ACCOUNT 的基类并执行强制转换,因为我想模拟运行时继承。(ACCOUNT不知道SOURCEACCOUNT)

我愿意接受任何建议;我可以在 SOURCEACCOUNT 类中对函数进行外部或类似操作吗?C++11工会?C++11呼叫转移?更改"this"指针?

谢谢

听起来你想创建一个SOURCEACCOUNT(或各种其他类),它接受对ACCOUNT的引用,并有一些封闭类委托的方法ACCOUNT

class SOURCEACCOUNT{
  ACCOUNT& account;
public:
  explicit SOURCEACCOUNT(ACCOUNT& a):account(a){}
  void withdraw(int amount){ account.withdraw(amount); }
  // other methods which can either call methods of this class
  // or delegate to account
};