Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <functional>
- #include <algorithm>
- template <class M = std::string, class E = int>
- E log(M msg, E error = 0)
- {
- std::cout << msg;
- return error;
- }
- class Entity
- {
- public:
- Entity()
- {
- }
- virtual ~Entity()
- {
- _update = nullptr;
- _render = nullptr;
- }
- void setUpdate(std::function<void(Entity*)> update)
- {
- _update = update;
- }
- void setRender(std::function<void(Entity*)> render)
- {
- _render = render;
- }
- void update()
- {
- if (_update != nullptr)
- _update(this);
- else
- log("- Entity update() not defined !\n");
- }
- void render()
- {
- if (_render != nullptr)
- _render(this);
- else
- log("- Entity render() not defined !\n");
- }
- std::string name()
- {
- return _name;
- }
- int _x = 0;
- int _y = 0;
- std::string _name = "NONAME";
- protected:
- std::function<void(Entity*)> _update = nullptr;
- std::function<void(Entity*)> _render = nullptr;
- private:
- };
- void updateTest(Entity *entity)
- {
- entity->_name = "now use updateTest !";
- entity->_x += 4;
- entity->_y += 4;
- }
- void updateTest2(Entity *entity)
- {
- entity->_name = "now use updateTest2 !";
- entity->_x += 8;
- entity->_y += 8;
- }
- void renderTest(Entity *entity)
- {
- log("=================================\n");
- log(" Name = "+ entity->name()+"\n");
- log(" X = ");log(entity->_x);log("\n");
- log(" Y = ");log(entity->_y);log("\n");
- log("=================================\n");
- }
- int add(int first, int second)
- {
- return first + second;
- }
- int main()
- {
- int vel = 2;
- Entity test;
- test.setRender(renderTest);
- test.setUpdate(updateTest);
- test.update();
- test.render();
- test.setUpdate(updateTest2);
- test.update();
- test.render();
- // use Lambda functions !
- test.setUpdate(
- [&](Entity*entity) // all access (read & write)
- //[=](Entity*entity) // read only
- //[](Entity*entity) // no access
- {
- vel = 10; // need [&]
- entity->_name = "now use lambda function !";
- entity->_x += 666 + vel; // need [=]
- entity->_y += 666;
- }
- );
- test.update();
- test.render();
- //std::function<int(int)> func = [](int i){return i*1980;};
- auto func = [](int i, int j){return i+(j*2);};
- //Rearrange function add!
- //auto newFunc = std::bind(func, std::placeholders::_2, std::placeholders::_1); // swap arguments order !
- auto newFunc = std::bind(func, 10, std::placeholders::_1); // default value of first argument !
- std::cout << "Lambda function = "<< func(2,4) << "\n";
- //std::cout << "new Lambda function = "<< newFunc(2,4) << "\n";
- std::cout << "new Lambda function = "<< newFunc(2) << "\n";
- return log("- Program terminated OK ! \n");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement