Advertisement
Guest User

Boost-Mpl documented but missing template

a guest
Jul 8th, 2013
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. /*
  2.  * main.cpp
  3.  *
  4.  *  Created on: Jul 8, 2013
  5.  *      Author: didier_m
  6.  */
  7.  
  8. #include <string>
  9. #include <iostream>
  10. #include <boost/mpl/at.hpp>
  11. #include <boost/mpl/map.hpp>
  12. #include <boost/mpl/pair.hpp>
  13.  
  14. // Minimal policy based design example (inspired from the freakycpp.com article)
  15. // I'll define a Foo class (let's imagine it actually does something)
  16. //  some member functions and include policy-defined logging.
  17.  
  18. // This is de default policy map:
  19. // It is just an empty map. Policy consumers may define their own defaults.
  20. typedef boost::mpl::map<> DefaultPolicy;
  21.  
  22. // This is the key used to identify the logging policy.
  23. // PK == policy key
  24. class LogPK;
  25.  
  26. // The default logging policy (noop)
  27. struct DefaultLogP
  28. {
  29.     static void log(const std::string& message) {}
  30. };
  31.  
  32. // Custom logging policies
  33. struct StdCoutLogPolicy
  34. {
  35.     static void log(const std::string& message) {
  36.         std::cout << message << std::endl;
  37.     }
  38. };
  39. struct StdCerrLogPolicy
  40. {
  41.     static void log(const std::string& message) {
  42.         std::cerr << message << std::endl;
  43.     }
  44. };
  45.  
  46. template<class TPolicy=DefaultPolicy> class Foo
  47. {
  48.     // Let's resolve the logging policy and make a typedef to it:
  49.     typedef typename boost::mpl::at<TPolicy, LogPK, DefaultLogP>::type LoggingPolicy;
  50.  
  51. public:
  52.     static void doBar(const std::string& message) {
  53.         LoggingPolicy::log(message);
  54.         // ...
  55.     }
  56. };
  57.  
  58. int main()
  59. {
  60.     // Once with the noop policy:
  61.     Foo<>::doBar("This message isn't supposed to show up");
  62.    
  63.     Foo<boost::mpl::map<boost::mpl::pair<LogPK, StdCoutLogPolicy> > >
  64.         ::doBar("Log on std::cout");
  65.     Foo<boost::mpl::map<boost::mpl::pair<LogPK, StdCerrLogPolicy> > >
  66.         ::doBar("Log on std::cerr");
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement