D
Denis Remezov
Valery said:hi All,
how to make a member function, which is virtual
not for a single object, but for the *pair* of objects?..
Here goes the skeleton of the code, which should
ideally print "ABCD":
------------------------------------
class A {};
struct A1 : public A {} a1;
struct A2 : public A {} a2;
struct S {};
struct S1 : public S {} s1;
struct S2 : public S {} s2;
void go(const A* pa, const S* sa) {
// ??
}
int main() {
go(&a1, &s1); // => "A"
go(&a1, &s2); // => "B"
go(&a2, &s1); // => "C"
go(&a2, &s2); // => "D"
return 0;
}
------------------------------------
But the question is how to obtain this without
dynamic_casting and accessing type info.
i.e. obtain just using usual "virtual" member
functions in C++.
thanks,
Valery
They usually call it "double dispatch". Try googling for "double dispatch",
"multi-methods" and "visitor pattern". Since the language provides no direct
support, you will have to imitate it (curiously, there is a discussion of
some "whys" in the "The Design and Evolution of C++" [Stroustrup]).
The Visitor Pattern would be my first choice to consider to implement
this. Note that it is asymmetrical in regards to the roles of A and S.
It has variations.
In the trivial illustration below, class A is a "visitor".
#include <iostream>
using namespace std;
struct S1;
struct S2;
struct A {
virtual void go1(S1&)=0;
virtual void go2(S2&)=0;
};
struct A1 : A {
void go1(S1& s) {
cout<<"A"<<endl;
}
void go2(S2& s) {
cout<<"B"<<endl;
}
};
struct A2 : A {
void go1(S1& s) {
cout<<"C"<<endl;
}
void go2(S2& s) {
cout<<"D"<<endl;
}
};
struct S {
virtual void go(A&) = 0;
};
struct S1 : S {
void go(A& a) {
a.go1(*this);
}
};
struct S2 : S {
void go(A& a) {
a.go2(*this);
}
};
int main() {
A1 a1;
A2 a2;
S1 s1;
S2 s2;
s1.go(a1);
s2.go(a1);
s1.go(a2);
s2.go(a2);
return 0;
}
Denis