How to do "derived" type extensions?
Suppose class B is a subtype of class A, i.e.,
class B : public A
{
...
};
Then, in C++, a pointer to type B can be treated as a pointer to type
A. So, I can do the following:
B *b;
A *a = b;
This morphism of types is what makes C++ so powerful.
But now how do I do the following kind of morphism? Suppose I have functions
void foo(const B &);
and
void bar(const A &);
I like to be able to declare a function pointer
void (*fp)(const B&);
and make "polymorphic" assignments like
p = foo; // this is ok in C++.
p = bar; // semantically this make sense, but C++ syntax won't
allow this!
I know the last line of code is not valid C++ because the function
signatures are required to be the same. However, on a semantic level,
I should be allowed to substitute calls to foo with calls to bar. This
is what I mean:
B b;
foo(b); // I can substitute the function foo in this line to
bar(b); // the function bar in this line.
So, at least on a semantic level I should be able to declare a
"polymorphic" function pointer that can points to both foo and bar
types.
void (*fp)(const B&) = bar;
fp(b); // here, b is passed as type A to fp since bar accepts
type A argument.
But I can't, because C++ doesn't work this way.
Now, I know the mantra "When in Rome, do as Romans." So, if this is
not a feature of C++, then I should rework a solution that is in C++.
But I'm just curious if anyone has a "good hack" to simulate this type
of polymorphism in C++?
--
-kira