Boost question about static method of a class
Hi all, Just wondering if I can do this with Boost: I have a number of classes that all have the same static method with the same arguments. I want to register these classes somewhere/somehow so that later on I can do something like: aClassName::StaticMethod(pData, len); // for example At runtime aClassName whould be the actual class, for example would resolve to: BobsClass::StaticMethod(pData, len); In Java I think I would use the class "Class" to do something like this, but dont know how in C++. Thanks for any help, -K __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com
kauai wrote:
Hi all,
Just wondering if I can do this with Boost:
I have a number of classes that all have the same static method with the same arguments. I want to register these classes somewhere/somehow so that later on I can do something like:
aClassName::StaticMethod(pData, len); // for example
At runtime aClassName whould be the actual class, for example would resolve to:
BobsClass::StaticMethod(pData, len);
In Java I think I would use the class "Class" to do something like this, but dont know how in C++.
I don't think Boost provides anything to help you with this, but it's not terribly difficult to do. I'm guessing you're actually trying to implement named factories, so here's an example of how to do that: #include <cstddef> #include <iostream> #include <map> #include <stdexcept> #include <string> #include <utility> class base { // definition omitted }; typedef base * factory_type(void *, std::size_t); // Singleton register of factory functions class factory_register { typedef std::map<std::string, factory_type *> map_type; factory_register() {} ~factory_register() {} map_type map_; public: // Get the register static factory_register & get() { static factory_register reg; return reg; } // Add function to registry void add(const std::string & name, factory_type * fun) { map_.insert(map_type::value_type(name, fun)); } // Call a factory function base * create(const std::string & name, void * p, std::size_t len) const { map_type::const_iterator it = map_.find(name); if (it == map_.end()) throw std::runtime_error("named factory not found"); return it->second(p, len); } }; class my_class : public base { my_class(void *, std::size_t); static bool dummy_; public: static base * create(void * p, std::size_t len) { return new my_class(p, len); } // other functions omitted }; // This variable is not used but its initialisation causes the factory // function to be registered. bool my_class::dummy_ = (factory_register::get().add("my_class", my_class::create), true);
participants (2)
-
Ben Hutchings
-
kauai