Static C ++ Submission Using Templates

Suppose I have C ++ code that looks like this:

class Base {
    virtual void dummy() = 0;
    // this is to generate a vtable, but note there is no virtual f()
};

class A : public Base {
public:
    void f() { /* ... */ };
    void dummy() {};
}

class B : public Base {
public:
    void f() { /* different implementation from A */ };
    void dummy() {};
}

template<class T1, class T2, class T3>
void doStuff(T1 &x, T2 &y, T3 &z) {
    for (i=1; i<100000; ++i) {
        x.f();
        y.f();
        z.f();
    }
}

The goal is to avoid invoking virtual functions f()during this inner loop to allow compiler optimization. (This is obviously a simplified version of my real code. See this more specific question for more details on my use case. )

This works fine if the doStuffargument types are known at runtime, but if they are not, then this fails:

int main() {
    Base *x = new A();
    Base *y = new B();
    Base *z = new A();

    doStuff(*x, *y, *z); 
    // oops - this instantiates to doStuff(Base &, Base &, Base &)
    // and there no Base::f().
}

to get around this (as suggested by this answer ), it seems to me that I should explicitly build a static dispatch function:

void doStuff(Base &x, Base &y, Base &z) {
    A *a_x = dynamic_cast<A*>(&x);
    B *b_x = dynamic_cast<B*>(&x);
    A *a_y = dynamic_cast<A*>(&y);
    B *b_y = dynamic_cast<B*>(&y);
    A *a_z = dynamic_cast<A*>(&z);
    B *b_z = dynamic_cast<B*>(&z);
    if (a_x && a_y && a_z) {
        doStuff(*a_x, &a_y, &a_z);
    } else if (a_x && a_y && b_z) {
        doStuff(*a_x, &a_y, &b_z);
    } 
    // ... and so on for all eight combinations of A and B.
}

, doStuff, , .

, : ? , - , , .

+1
2

: "static dispatch" - , ... . .

dynamic_cast - , dynamic_cast OO. , , dynamic_cast (dynamic_cast !), , f() virtual .

, , - 8 , , , ++. , / , - , / . doStuff() "" , , ( enum gettype + ), , .

: ++. , , ++: , , ...

+1

. . ( , 3 ). - map<tuple<type_info, type_info, type_info>, StuffDoer> ( doStuff dynamic_cast ).

0

Source: https://habr.com/ru/post/1529720/


All Articles