I would like some feedback if the follow code is standard compliant, and are
there any obvious redundancies or inefficiencies? The purpose of the code is
to emulate the behaviour of a struct FuBar which implements an interface
InterfaceFuBar which contains two functions Fu and Bar. The goal is to do so
without resorting to virtual functions.
#include <iostream>
template<typename SELF> struct ITABLE_InterfaceFuBar {
void(SELF::*Fu)();
void(SELF::*Bar)();
};
struct InterfaceFuBar {
struct DUMMY_InterfaceFuBar {
void Fu() { };
void Bar() { };
};
struct DUMMY_ITABLE_InterfaceFuBar : public
ITABLE_InterfaceFuBar<DUMMY_InterfaceFuBar> { };
DUMMY_InterfaceFuBar* mpObject;
DUMMY_ITABLE_InterfaceFuBar* mpTable;
InterfaceFuBar(void* pObject = NULL, void* pTable = NULL) {
mpObject = (DUMMY_InterfaceFuBar*)pObject;
mpTable = (DUMMY_ITABLE_InterfaceFuBar*)pTable;
};
void Fu() { (mpObject->*(mpTable->Fu))(); };
void Bar() { (mpObject->*(mpTable->Bar))(); };
};
template<typename I, typename M> struct Implementor {
operator I() { return I(NULL, NULL); };
};
template<typename M> struct Implementor<InterfaceFuBar, M> {
operator InterfaceFuBar() {
static ITABLE_InterfaceFuBar<M> tmp = { M::Fu, M::Bar };
return InterfaceFuBar(this, (void*)&tmp);
};
};
struct FuBar : public Implementor<InterfaceFuBar, FuBar> {
void Fu() { std::cout << "fu" << std::endl; };
void Bar() { std::cout << "bar" << std::endl; };
};
int main() {
FuBar f;
InterfaceFuBar i = f;
i.Fu();
std::cin.get();
return 0;
}
--
Christopher Diggins
http://www.cdiggins.com
http://www.heron-language.com