Originally my idea was to use a struct of function pointers and 'iterate' over them to arrive at a different pointer. However, I found that pointer arithmetic apparently doesn't work on function pointers. :( That is when I thought of union. It was only later that I realized the union construct can solve the task by itself. But since I already posted my solution, there was no point in 'watering it down'. ;) Another thing I thought of is overloading virtual functions with different return types. But it would require at least a downcast of the instance pointer:
class base {
public:
virtual ~base() {}
virtual int* foo(int i) { return &i; }
};
class derived : public base {
public:
virtual ~derived() {}
virtual int foo(int i) { return i; } // overrides base::foo()
};
int* bar(int i) {
base* caster = new derived; // implicit downcast here
int* pi = caster->foo(i); // this is the actual 'reinterpret cast'
delete caster;
return pi:
}
I wonder if I could get this to work if I put part of the code inside a constructor, before the construction of the vtable - but then the behaviour would be undefined :doh: