How to obtain a pointer out of a C++ vtable?

前端 未结 5 984
有刺的猬
有刺的猬 2020-12-14 09:15

Say you have a C++ class like:

class Foo {
 public:
  virtual ~Foo() {}
  virtual DoSomething() = 0;
};

The C++ compiler translates a call

5条回答
  •  萌比男神i
    2020-12-14 09:49

    I can think of two other solutions, rather than digging in the C++ object model.

    The first (and obvious): Generic Programming (aka templates)

    Don't use a base class, refactor the methods that depend on the base class so that they take the "Strategy" as a template argument. This will completely eliminate the virtual calls.

    The second, less obvious, is to reverse the dependencies.

    Instead of injecting the strategy in the algorithm, inject the algorithm in the strategy. This way you will have a single virtual call, at the beginning, and then it will proceed "normally". Templates can help once again here.

提交回复
热议问题