Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * main.cpp
- *
- * Created on: Jul 8, 2013
- * Author: didier_m
- */
- #include <string>
- #include <iostream>
- #include <boost/mpl/at.hpp>
- #include <boost/mpl/map.hpp>
- #include <boost/mpl/pair.hpp>
- // Minimal policy based design example (inspired from the freakycpp.com article)
- // I'll define a Foo class (let's imagine it actually does something)
- // some member functions and include policy-defined logging.
- // This is de default policy map:
- // It is just an empty map. Policy consumers may define their own defaults.
- typedef boost::mpl::map<> DefaultPolicy;
- // This is the key used to identify the logging policy.
- // PK == policy key
- class LogPK;
- // The default logging policy (noop)
- struct DefaultLogP
- {
- static void log(const std::string& message) {}
- };
- // Custom logging policies
- struct StdCoutLogPolicy
- {
- static void log(const std::string& message) {
- std::cout << message << std::endl;
- }
- };
- struct StdCerrLogPolicy
- {
- static void log(const std::string& message) {
- std::cerr << message << std::endl;
- }
- };
- template<class TPolicy=DefaultPolicy> class Foo
- {
- // Let's resolve the logging policy and make a typedef to it:
- typedef typename boost::mpl::at<TPolicy, LogPK, DefaultLogP>::type LoggingPolicy;
- public:
- static void doBar(const std::string& message) {
- LoggingPolicy::log(message);
- // ...
- }
- };
- int main()
- {
- // Once with the noop policy:
- Foo<>::doBar("This message isn't supposed to show up");
- Foo<boost::mpl::map<boost::mpl::pair<LogPK, StdCoutLogPolicy> > >
- ::doBar("Log on std::cout");
- Foo<boost::mpl::map<boost::mpl::pair<LogPK, StdCerrLogPolicy> > >
- ::doBar("Log on std::cerr");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement