(C++) Strategy Design Pattern Example: StrToDouble
February 24, 2017 · View on GitHub
(C++) Strategy Design Pattern Example: StrToDouble
Strategy Design Pattern Example: StrToDouble is an example of a Strategy Design Pattern.
You can convert this to a compile-time Strategy Design Pattern, for example to compile-time Strategy Design Pattern example: StrToDouble.
Technical facts
Operating system(s) or programming environment(s)
Lubuntu 12.10 (quantal)
Qt Creator 2.5.2
- G++ 4.7.2
Libraries used:
STL: GNU ISO C++ Library, version
4.7.2
Qt project file: CppStrategy Design Pattern Example: StrToDouble.pro
TEMPLATE = app CONFIG += console CONFIG -= qt QMAKE_CXXFLAGS += -std=c++11 -Wall -Wextra -Weffc++ SOURCES += main.cpp
main.cpp
#include <boost/lexical_cast.hpp> #include <boost/shared_ptr.hpp> #include <string> ///A Strategy Design Pattern struct StrToDoubleStrategy { virtual double StrToDouble(const std::string& s) const = 0; virtual ~StrToDoubleStrategy() {} }; struct StrToDoubleStrategyStl : public StrToDoubleStrategy { double StrToDouble(const std::string& s) const { return std::atof(s.c_str()); } }; struct StrToDoubleStrategyBoost : public StrToDoubleStrategy { double StrToDouble(const std::string& s) const { return boost::lexical_cast<double>(s); } }; struct StrToDoubleStrategyCpp11 : public StrToDoubleStrategy { double StrToDouble(const std::string& s) const { return std::stof(s); } }; struct Converter { Converter(const StrToDoubleStrategy * strategy) : m_strategy(strategy) { assert(m_strategy); } double StrToDouble(const std::string& s) const { return m_strategy->StrToDouble(s); } private: boost::shared_ptr<const StrToDoubleStrategy> m_strategy; }; #include <cassert> int main() { const Converter a(new StrToDoubleStrategyStl); const Converter b(new StrToDoubleStrategyBoost); const Converter c(new StrToDoubleStrategyCpp11); assert( std::abs(12.34 - a.StrToDouble("12.34")) < 0.000001); assert( std::abs(12.34 - b.StrToDouble("12.34")) < 0.000001); assert( std::abs(12.34 - c.StrToDouble("12.34")) < 0.000001); }