I have the following code:struct AInterface {    XXX some_method(/* some params */) = 0;};void foo(const AInterface & a) {    do_work();    while (x) {        do_work_2();        foo_process_input(a);    }    return some_value();}void foo_process_input(const AInterface & a) {    do_inefficient(a);}However, I recently realized that some objects implementing AInterface are actually following a more specialized interface, so that I could do:struct BInterface : AInterface {     YYY some_better_method(/* some other params */) = 0;};void foo_process_input(const BInterface & b) {    do_efficient(b);}in order to improve the performance of my code in certain cases. Note: the signatures of some_method and some_better_method do not allow using one over the other.However, I'm wondering how I should modify foo in order to accommodate this change and avoid duplicating the code. As I can see, it seems I have two options:Templatize foo to accept both interfacesRely on dynamic_casttemplate <typename Interface>void foo(const Interface & a_or_b) {    do_work();    while (x) {        do_work_2();        foo_process_input(a_or_b);    }    return some_value();}The templatized solution requires less changes, but has the disadvantage that the compiler is going to duplicate all the do_work code which does not really depend on the input. In addition, this makes uglier errors, as the actual type of a_or_b is only checked upon calling foo_process_input, which being an internal of foo could be confusing for the user.void foo(const AInterface & a_or_b) {    do_work();    auto * binterface = dynamic_cast<BInterface*>(&a_or_b);    while (x) {        do_work_2();        if (binterface) foo_process_input(*binterface);        else foo_process_input(a_or_b);    }    return some_value();}The dynamic_cast solution should work and not cost too much in terms of performance, but I've always been wary of runtime type checking, and it makes me wonder if I could somehow improve on the interface definition.Do you have any suggestion on how to approach this problem?
Handling more specialized interface with no code duplication
interfaces;c++11;templates