Re: How to do "derived" type extensions?
On 2008-01-09 13:46:24 -0500, LR <lruss@superlink.net> said:
Kira Yamato wrote:
On 2008-01-08 12:17:35 -0500, LR <lruss@superlink.net> said:
Kira Yamato wrote:
On 2008-01-08 09:18:53 -0500, LR <lruss@superlink.net> said:
Kira Yamato wrote:
Suppose class B is a subtype of class A, i.e.,
class B : public A
{
...
};
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!
Would it be acceptable to create a function,
void bar(const B &);
You mean
void foo(const B &);
No, that's not what I meant. I don't think that I made myself clear,
so I'll try again.
Untested, and not complete...
This is what I think you started with.
class A {
};
class B : public A {
};
void foo(const B &) {
}
void bar(const A &) {
}
now I suggest adding this function
void bar(const B &b) {
::bar( reinterpret_cast<const A&>(b) );
}
so you can
void (*fp)(const B&);
and
B b;
fp = bar; // will assign the address of void bar(const B &) to fp
fp(b);
fp = foo;
fp(b);
Yes. This is a nice work-around in the sense that it is direct and
seemingly not too much artifact.
Your solution is similar to the adaptor pattern (or am I misusing the
terminology here?).
I suppose in some ways, maybe not in others. However, consider this
well known, although I don't know the source, quote: "any [programming]
problem can be solved by introducing an extra level of indirection."
Thanks for the suggestion.
You're welcome.
Please don't overlook Pete Becker's correction and advice to use
static_cast instead of reinterpret_cast elsethread.
Yes. I've read that.
BTW, I've been thinking about this, and wondering about what you want
to do because I suspect this might be a little bit of a maintenance
problem if you're using this extensively in your code and your class
structure changes.
It started as a purely academic question. Since I notice the power of
C++ comes from the abstraction that allows writing codes which operates
on compatible types, I wonder if this concept could extend to "derived"
types too.
By "derived" types, I mean types that depend on object types, e.g.,
functions with parameters of polymorphic types, or templates that
depend on object types. How would you declare pointers to those things?
We can even go further with this idea, like types that depend on these
derived types. For example, a function whose parameter is a template
of object types.
--
-kira