info

あっびゃっばばのためにテンプレートを使うStrategyパターン

-Weffc++?後回し!

Report.hpp

#pragma once

#include <string>
#include <vector>

using namespace std;

template <class T>
class Report
{
 public:
  Report (T*);
  void output_report ();
  string title;
  vector<string> text;

 private:
  T* formatter;
};

template <class T>
Report<T>::Report (T *informatter)
{
  title = "月次報告";
  text.push_back ("順調");
  text.push_back ("最高の調子");

  formatter = informatter;
}

template <class T>
void Report<T>::output_report ()
{
  formatter->output_report (this);
}

Formatters.hpp

#include "Report.hpp"

class HTMLFormatter
{
 public:
  void output_report (Report<HTMLFormatter>*);
};

class PlainTextFormatter
{
 public:
  void output_report (Report<PlainTextFormatter>*);
};

Formatters.cpp

#include "Report.hpp"
#include "Formatters.hpp"
#include <iostream>
#include <string>
#include <vector>

void PlainTextFormatter::output_report (Report<PlainTextFormatter> *context)
{
  cout << "*** " + context->title + " ***" << endl;
  for (vector<string>::iterator line = context->text.begin (); line != context->text.end (); ++line)
    {
      cout << *line << endl;
    }
}

void HTMLFormatter::output_report (Report<HTMLFormatter> *context)
{
  cout << "<html>" << endl;
  cout << "  <head>" << endl;
  cout << "    <title>" + context->title + "</title>" << endl;
  cout << "  </head>" << endl;
  cout << " <body>" << endl;
  for (vector<string>::iterator line = context->text.begin (); line != context->text.end (); ++line)
    {
      cout << "    <p>" + *line + "</p>" << endl;
    }
  cout << "  </body>" << endl;
  cout << "</html>" << endl;
}

stra.cpp

#include "Formatters.hpp"
#include "Report.hpp"

int main (int args, char *argv[])
{
  Report<HTMLFormatter> *htmlreport = new Report<HTMLFormatter> (new HTMLFormatter ());
  Report<PlainTextFormatter> *textreport = new Report<PlainTextFormatter> (new PlainTextFormatter ());

#ifdef HTML
  htmlreport->output_report ();
#endif /*HTML*/

#ifdef TEXT
  textreport->output_report ();
#endif /*TEXT*/

  delete htmlreport;
  delete textreport;
}