简体   繁体   中英

C++ Store a function from a member class property in another class

I'm writing a little game that works on a 2D tileset. The idea is that there will be some cells (position X, position Y) where if the player steps, it will trigger an event, so I'm creating a map<cell_position, function to trigger> .

The problem is that this function it will be in the World class, that contains the Npc member, and I want to store the Npc public function teleport as the value from the map, as I can display in the next snippet:

std::unordered_map<std::pair<int, int>, std::function<void()>> actionCells =
 { std::make_pair(10, 1), std::bind(mPlayerNpc->teleport, 3, 3)) };

Is this possible to do? Because I'm getting the next errors:

error: invalid use of non-static member function 'void Npc::teleport(int, int)'

--Edit-----------------------------------

If I don't want to use a Lambda, is it done like this?

std::unordered_map<std::pair<int, int>, std::function<void()>> actionCells =
   { std::make_pair(10, 1), [&]() {mPlayerNpc->teleport(3, 3); } };

Passing class instance to std::bind should work. Something like:

std::unordered_map<std::pair<int, int>, std::function<void(int x, int y)>> actionCells =
 { std::make_pair(10, 1), std::bind(&mPlayerNpc::teleport, mPlayerNpc 3, 3)) };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM