fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <functional>
  4. #include <algorithm>
  5. #include <iterator>
  6. #include <sstream>
  7.  
  8. using namespace std;
  9.  
  10. struct BaseGoDeeper {
  11. virtual void operator()(int i) = 0;
  12. ~BaseGoDeeper() {};
  13. };
  14.  
  15. struct A : BaseGoDeeper {
  16. void operator()(int /*i*/) { cout << "A" << endl; }
  17. };
  18.  
  19. struct B : BaseGoDeeper {
  20. void operator()(int /*i*/) { cout << "B" << endl; }
  21. };
  22.  
  23. struct SubAlgorithm {
  24. BaseGoDeeper& a_;
  25. SubAlgorithm (BaseGoDeeper& a) : a_(a) {}
  26. void operator()(int i) {
  27. // do some stuff and then do
  28. a_(i);
  29. }
  30. };
  31.  
  32. template<typename SubAlgorithm, typename Collection>
  33. void Alrogirthm(SubAlgorithm& f, Collection& stuff) {
  34. // In my code f is invoked ~ 1e9 times (it's a loop that is executed
  35. // ~ 1e6 times, and stuff.size() is ~1000). The application spends ~90% of
  36. // it's time in this function. But for the sake of example:
  37. for_each(stuff.begin(), stuff.end(), f);
  38. }
  39.  
  40. BaseGoDeeper* CreateGoDeeper(bool runtime_flag) {
  41. if (runtime_flag) {
  42. return new A();
  43. }
  44. return new B();
  45. }
  46.  
  47. int main(int , char**) {
  48. stringstream ss;
  49. ss << true << " " << false;
  50.  
  51. vector<int> stuff;
  52. stuff.push_back(1);
  53.  
  54. while (ss.good()) {
  55. bool runtime_flag;
  56. ss >> runtime_flag;
  57.  
  58. BaseGoDeeper* go_deeper_algorithm = CreateGoDeeper(runtime_flag);
  59. SubAlgorithm sub_algorithm(*go_deeper_algorithm);
  60. Alrogirthm(sub_algorithm, stuff);
  61. delete go_deeper_algorithm;
  62. }
  63. return 0;
  64. }
Success #stdin #stdout 0s 3032KB
stdin
Standard input is empty
stdout
A
B