Ways to detect whether a C++ virtual function has been redefined in a derived class

前端 未结 9 1313
不知归路
不知归路 2020-12-01 14:10

In brief: From a C++ base-class pointer which points to an instance of a derived class, how can one determine at run-time whether a non-pure virtual functio

相关标签:
9条回答
  • 2020-12-01 14:33

    It can't be done the way you're trying. There's no way for the base class's functions to know whether or not a virtual function they implement has been overridden without being explicitly told so.

    It would seem you need to go back to the drawing board. Not exactly sure how I'd solve your design issue, but what you're trying now I know simply won't work.

    0 讨论(0)
  • 2020-12-01 14:36

    You can't check for override of virtual function portably.

    You need to bring the knowledge to the Solver, preferably via type as opposed to run-time flag.

    One (type-based) way is to check for presence or absence of a interface, via dynamic_cast.

    A probably better way is to provide overloads of solve function, in your case the Solver constructor.

    Probably better advice could be given if you provided a more concrete description of the problem. It does remind of typical situation where someone (1) needs to solve some problem P, (2) envisions technical approach X as a solution to P, (3) discovers that X doesn't cut it, and (4) asks how to make X work for a vague description of P, or even for some unrelated problem Q. The details of original problem P will often suggest a much better solution than X, and the problems of making X work, irrelevant to solving P.

    0 讨论(0)
  • 2020-12-01 14:36

    And what if you didn't use virtual methods ?

    At this point I am think of a template-base solution. It is possible (albeit not so easy) to use templates to detect whether a given class has a method with a certain signature, or not. Once identified, you can switch, at compile-time, between the lightweight scheme and the heavy scheme.

    Note that I do not suggest that all the code be templated, the templated code will only cover the Template (Design Pattern) part of the solution, and the heavy-lifting can be done with regular functions to cut on dependencies.

    Also, this can be completely transparent for the clients, providing you do not alter the signature of the methods.

    0 讨论(0)
提交回复
热议问题