tr1 function (memo)

I make the sample code in Item 35 be compiled. Add a line of code to use class directly. It is memo for me to remember it.

 

#include <tr1/memory>
#include <string>
#include <iostream>
#include <tr1/functional>
using namespace std;

class GameCharacter;

int defaultHealthCalc(const GameCharacter& gc);

class GameCharacter {
  public:
    typedef tr1::function<int (const GameCharacter&)> HealthCalcFunc;
    
    explicit GameCharacter(HealthCalcFunc hcf = defaultHealthCalc) 
      : healthFunc(hcf)
    {
    }

    int healthValue() const {
      return healthFunc(*this);
    }

  private:
    HealthCalcFunc healthFunc;
};

// function
short calcHealth(const GameCharacter& gc) {
}

// struct
struct HealthCalculator {
  int operator() (const GameCharacter&) const {
  }
};

// class
class GameLevel {
  public:
    float health(const GameCharacter& gc) const {
    }
};

class EvilBadGuy: public GameCharacter {
  public:
    EvilBadGuy(HealthCalcFunc hcf) : GameCharacter(hcf) {
    }
};

class EyeCandyCharacter: public GameCharacter {
  public:
    EyeCandyCharacter(HealthCalcFunc hcf) : GameCharacter(hcf) {
    }
};

int main(int argc, const char *argv[]) {
  EvilBadGuy ebg1(calcHealth);
  EyeCandyCharacter ecc1(HealthCalculator);

  GameLevel currentLevel;
  EvilBadGuy ebg2(tr1::bind(&GameLevel::health,
                            currentLevel,
                            tr1::placeholders::_1)
      );
  // class is similar to struct
  EvilBadGuy xx(GameLevel);
  return 0;
}
 

你可能感兴趣的:(function)