(C++) Compile-time Strategy Design Pattern example: StrToDouble
February 24, 2017 · View on GitHub
(C++) Compile-time Strategy Design Pattern example: StrToDouble
Compile-time Strategy Design Pattern example: StrToDouble is a compile-time Strategy Design Pattern.
You can also employ a run-time Strategy Design Pattern.
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: CppCtStrategyDesignPatternExampleStrToDouble.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 <string> ///A compile-time Strategy Design Pattern enum CtStrategyPolicy { Use_stl, Use_boost, Use_cpp11 }; template <CtStrategyPolicy> struct CtStrategy { static double StrToDouble(const std::string& s); }; template<> double CtStrategy<Use_stl>::StrToDouble(const std::string& s) { return std::atof(s.c_str()); } template<> double CtStrategy<Use_boost>::StrToDouble(const std::string& s) { return boost::lexical_cast<double>(s); } template<> double CtStrategy<Use_cpp11>::StrToDouble(const std::string& s) { return std::stof(s); } #include <cassert> int main() { const CtStrategy<Use_stl> a; const CtStrategy<Use_boost> b; const CtStrategy<Use_cpp11> c; 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); }