D
Default User
Andrey Tarasevich said:No. That poster is flat out incorrect.
Very interesting. Below will be a more complete example of what I'm
proposing to do in the real code. That is, the managing of the handlers,
storing the pointers, retrieving the correct one based on op code, and
calling of the function pointer, take place in the base class. All the
derived class has to do is set up the relationships between op codes and its
member function pointers to implement the operation set for that particular
module.
If this is still legal, then I'd be on pretty firm ground with my plan for
the actual code.
Brian
#include <iostream>
#include <map>
#define CALL_HANDLER(object,ptrToMember)((object).*(ptrToMember))
class tbase
{
public:
typedef int (tbase::*HandlerPtr)(int);
void write(int data, int code)
{
std::map<int, HandlerPtr>::iterator it;
it = handlers.find(code);
if (it != handlers.end())
{
// Found, call the function pointer
CALL_HANDLER(*this, it->second)(data);
}
else // unhandled code
{
// error handling
}
}
void list()
{
std::map<int, HandlerPtr>::iterator it = handlers.begin();
std::cout << "Supported Op codes:\n";
while (it != handlers.end())
{
std::cout << it->first << "\n";
it++;
}
}
protected:
tbase() : baseDataStore(0)
{
}
virtual ~tbase()
{
}
std::map<int, HandlerPtr> handlers;
int baseDataStore;
};
class test : public tbase
{
public:
test() : testDataStore(0)
{
handlers[0] = static_cast<HandlerPtr>(&test::H0);
handlers[4] = static_cast<HandlerPtr>(&test::H4);
}
virtual ~test()
{
}
virtual int H0(int data)
{
baseDataStore = data;
std::cout << "test::H0: " << baseDataStore << "\n";
return data;
}
int H4(int data)
{
testDataStore = data;
std::cout << "test::H4: " << testDataStore << "\n";
return data;
}
private:
int testDataStore;
};
int main()
{
test t;
t.list();
t.write(123, 0);
t.write(456, 4);
return 0;
}