Wednesday, December 01, 2010

some fun with C++

Was playing around with C++, and found that you can actually use a base class member function pointer to call functions defined in derived class. Round about way, but useful for implementing stuff like: http://en.wikipedia.org/wiki/Future_%28programming%29

Here is an example snippet:

#include ...
class Base {
public:
typedef void (Base::*WhoPtr)();
};
class D1: public Base {
public:
void WhoAmI() const;
};
class D2: public Base {
public:
void WhoAmI() const;
};
void D1::WhoAmI() const {
std::cout << "I am D1" << std::endl;
}
void D2::WhoAmI() const {
std::cout << "I am D2" << std::endl;
}
void run(Base::WhoPtr fptr) {
Base base;
(base.*fptr)();
}
int main(int argc, char **argv ) {
Base::WhoPtr func;
func = (void (Base::*)()) &D1::WhoAmI;
run(func);
func = (void (Base::*)()) &D2::WhoAmI;
run(func);
return 0;
}

2 comments:

swagat said...

Hi Ganesh, can you explain how this particular feature of c++ helps in implementing futures?

Ganesh said...

hi swagat,

sorry for replying late. the post just gives a way to create a template class for implementing futures. however this is not a complete implementation, it is just one component, and one of the ways it could be done. you still need to write wrappers for appropriate threading library to do the real work.

for this particular case, i will not be able to share actual source as this was implemented for a proprietary codebase.

hope this helps
ganesh