Re: using compilers' internal virtual table information
On 12/30/2010 8:15 AM, Hicham Mouline wrote:
hello,
1) baseptr->f1()
When a base class has virtual member functions, and a reference or a pointer
to that base instance is passed around the code, client code can call those
functions and the runtime will correctly call the appropriate function
applicable to the actual type of the instance passed around.
yes.
2) widget* create_widget( const base& )
Now there are cases where the client code receives such as base pointer or
reference, and requires a polymorphic behaviour similar to the above,
however the client code cannot/should not change the class definition. An
example I have is separate application code from GUI code.
1 solution is to have the client code aware of all possible most derived
types from the base class, in some sort of type list, try to dynamic_cast<>
the received base pointer/reference to each most derived type until success,
and then do whatever needs doing.
This reduces the dependencies. The base and derived classes know nothing
about the existence of a GUI.
This dynamic cast trial appears similar to what the compilers must do
internally, though it's possibly slower.
Is there a way to use the compiler's internal methods/information to realize
the above?
it is unclear what is being asked exactly...
any methods in a base class may be called in inherited classes, as in 1.
if you want to provide callbacks without creating a derived class, then
a possible option is to use function pointers...
if one wants to be able to plug 2 different classes together without
having to have each depend on each other, and without creating a new
class, then an option is to use a pointer, such as "void *", and then
use this in combination with the function pointers.
say:
class Foo
{
public:
void *bar_data;
void (*bar_method)(void *data);
};
then one can trampoline over to a method in bar via:
Foo *foo;
foo->bar_method(foo->bar_data);
with a function like:
void bar_method_f(void *data)
{
Bar *bar;
bar=(Bar *)data;
bar->method();
}
which could be stuffed into 'foo->bar_method'...
or such...