Created
October 11, 2017 18:44
-
-
Save Intey/b622d9db1a8d311eacac496fd01d863b to your computer and use it in GitHub Desktop.
C++14 style
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <vector> | |
#include <functional> | |
#include <memory> | |
#include <iostream> | |
using namespace std; | |
class Unit | |
{ | |
public: | |
int health; | |
}; | |
using UnitPtr=shared_ptr<Unit>; | |
class Trap | |
{ | |
public: | |
Trap(int p):power(p) | |
{ | |
cout << "trap maked with power " << p << endl; | |
} | |
int power = 0; | |
}; | |
void activate(Trap const& t, UnitPtr const& target) | |
{ | |
target->health -= t.power; | |
} | |
int main(int argc, char *argv[]) | |
{ | |
// only one Trap initialization | |
auto forestTrapIt = bind(activate, Trap{10}, placeholders::_1); | |
// lambda capture move | |
auto mountainTrapIt = [trap=Trap{20}](auto t) { activate(trap, t); }; | |
// like simple definition of function, but in runtime | |
auto waterTrapIt = [](auto t) | |
{ | |
static const Trap trap{30}; | |
activate(trap, t); | |
}; | |
UnitPtr h { new Unit{100} }; | |
forestTrapIt(h); | |
forestTrapIt(h); | |
mountainTrapIt(h); | |
mountainTrapIt(h); | |
waterTrapIt(h); | |
waterTrapIt(h); | |
cout << h->health << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment