Simplified namespace nesting.
Refactor virtual setter method name.
This commit is contained in:
Jens Luedicke
2010-09-19 22:37:57 +02:00
parent 6be687ae44
commit db168ca56e
2 changed files with 60 additions and 55 deletions

View File

@@ -4,17 +4,13 @@
#include <boost/lexical_cast.hpp> #include <boost/lexical_cast.hpp>
namespace settable {
namespace setter {
namespace string2type { namespace string2type {
namespace helper {
template<> template<>
int convert<int>(const std::string &value) { int convert<int>(const std::string &value) {
return boost::lexical_cast<int>(value); return boost::lexical_cast<int>(value);
} }
}
}
}
} }
struct foo : settable::settable { struct foo : settable::settable {

View File

@@ -4,58 +4,67 @@
#include <map> #include <map>
#include <string> #include <string>
#include <boost/assert.hpp>
#include <boost/shared_ptr.hpp> #include <boost/shared_ptr.hpp>
namespace settable {
namespace setter {
namespace string2type { namespace string2type {
namespace helper {
template<typename T> template<typename T>
T convert(const std::string &value); T convert(const std::string &value);
} }
}
namespace settable {
class abstract_setter { class abstract_setter {
public: public:
virtual void operator=(const std::string &value) = 0; virtual void set_value(const std::string &value) = 0;
}; };
template<typename T> template<typename T>
class setter: public abstract_setter { class setter: public abstract_setter {
public: public:
setter(void *p) : ptr(p) { setter(void *p)
: ptr(p) {
BOOST_ASSERT(ptr != 0); BOOST_ASSERT(ptr != 0);
} }
virtual void operator=(const std::string &value) { virtual void set_value(const std::string &value) {
T *ptrT = static_cast<T*>(ptr); T *ptrT = static_cast<T*>(ptr);
BOOST_ASSERT(ptrT != 0); BOOST_ASSERT(ptrT != 0);
*ptrT = string2type::helper::convert<T>(value); *ptrT = string2type::convert<T>(value);
} }
void *ptr; void *ptr;
}; };
}
class settable { class settable {
public: public:
void set_attribute(const std::string &attr, const std::string &value) { void set_attribute(const std::string &attr, const std::string &value) {
boost::shared_ptr<setter::abstract_setter> setter = setters[attr]; setters_map::iterator it = setters.find(attr);
if (setter) { if (it != setters.end()) {
*setter = value; it->second->set_value(value);
} }
} }
template<typename T> template<typename T>
void register_setter(const std::string &name, void *ptr) { void register_setter(const std::string &name, T *ptr) {
setters.insert(std::make_pair(name, boost::shared_ptr<setter::abstract_setter>(new setter::setter<T>(ptr)))); typedef setter<T> specific_setter;
setter_ptr setter(new specific_setter(ptr));
setters.insert(std::make_pair(name, setter));
} }
private: private:
std::map< std::string, boost::shared_ptr<setter::abstract_setter> > setters; typedef boost::shared_ptr<abstract_setter> setter_ptr;
typedef std::map<std::string, setter_ptr> setters_map;
setters_map setters;
}; };
} }
#endif /* SETTABLE_HPP */ #endif /* SETTABLE_HPP */