Re: How to invoke the methods of an object selecting them from a
table
This is a MIME GnuPG-signed message. If you see this text, it means that
your E-mail or Usenet software does not support MIME signed messages.
The Internet standard for MIME PGP messages, RFC 2015, was published in 1996.
To open this message correctly you will need to install E-mail or Usenet
software that supports modern Internet standards.
--=_mimegpg-commodore.email-scan.com-28765-1202213457-0001
Content-Type: text/plain; format=flowed; charset="US-ASCII"
Content-Disposition: inline
Content-Transfer-Encoding: 7bit
Stefano Sabatini writes:
This is my solution for subject:
#include <string>
#include <iostream>
using namespace std;
class DumbThing {
public:
void sayFoo() { cout << "Foo!" << endl; }
static void sayFoo(DumbThing &t) {
t.sayFoo();
}
void sayBar() { cout << "Bar!" << endl; }
static void sayBar(DumbThing &t) {
t.sayBar();
}
};
struct ClassMethod {
string name;
void (*method)(DumbThing &);
};
int main(void) {
struct ClassMethod DumbThingMethods[] = {
{ "sayFoo", &DumbThing::sayFoo },
{ "sayBar", &DumbThing::sayBar }
};
int DumbThingMethodsNum = sizeof(DumbThingMethods) / sizeof(ClassMethod);
DumbThing t;
for (int i=0; i < DumbThingMethodsNum; i++)
DumbThingMethods[i].method(t);
return 0;
}
The problem with this solution is that I have to create for each
method a corresponding static function, can you contrive a solution
which doesn't require this?
Many thanks in advance for any advice.
You want to use class member pointers:
// Declare:
class Foo {
public:
void x();
void y();
};
// Don't use arrays, when you really want a map:
std::map<std::string, void (Foo::*)() > methods;
// Initialize:
methods["x"]= &Foo:x;
methods["y"]= &Foo:y;
// Invoke some method on an object.
void callFoo(Foo *obj, std::string methodname)
{
std::map<std::string, void (Foo::*)() >::iterator p=
methods.find(methodname);
if (p == methods.end())
throw "You are a bozo";
(obj->*(p->second))();
}
--=_mimegpg-commodore.email-scan.com-28765-1202213457-0001
Content-Type: application/pgp-signature
Content-Transfer-Encoding: 7bit
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (GNU/Linux)
iD8DBQBHqFJRx9p3GYHlUOIRAjQKAJ9SyKDHF8LQp/dJ9VwY/L9MZ/KcuACeIzwA
ZMvZoGtyo21uvpeIpqAIUoQ=
=CYcU
-----END PGP SIGNATURE-----
--=_mimegpg-commodore.email-scan.com-28765-1202213457-0001--