我有一个应用程序正在为文明 V 创建地图。作为一个有趣的设计选择,我决定创建几个函数来为我循环遍历地图。这样,我可以将函数指针或 lambda 函数传递给该函数,该函数通过整个地图对每个图块执行某些操作。这背后的原因是,如果我或其他人会更改地图的存储方式(从 2D 数组到 2D 矢量或其他),则只需更改一个函数而不是整个代码库。
现在的问题,这里是一些代码。
错误代码。
case ALL_SNOW:
m.loop_through_limit([] (Tile* t) {
t = new Snow(t->get_x(), t->get_y());
return t;
}, x, y, width, height);
break;
case PTN_ONE:
m.loop_through_limit([&] (Tile* t) {
int cur_x = t->get_x();
int cur_y = t->get_y();
t = new Plains(cur_x, cur_y);
// if (y <= height/4 || y >= (height*3)/4) {
// Top quarter rows and bottom quarter rows
// t = new Ocean(cur_x, cur_y);
// } else if (cur_x <= width/4) {
// Leftmost columns
// t = new Ocean(cur_x, cur_y);
// } else if (cur_x >= (width*3)/4) {
// Rightmost columns
// t = new Desert(cur_x, cur_y);
// }
return t;
}, x, y, width, height);
break;
来自头文件的定义。
void loop_through(void (*)(Tile* t));
void loop_through_limit(Tile* (*)(Tile* t), int start_x, int start_y, int width, int height);
现在,除了注释掉的代码之外,每种情况下的区别并不大。这工作正常。当我注释掉 if 语句块时,这就是我的输出。
c++ -c -g -O3 -ffast-math -Wall -Weffc++ -std=c++0x -o tile_block.o tile_block.cpp
tile_block.cpp: In static member function ‘static void TileBlock::write(Map&, TileBlock::Patterns, int, int, int, int)’:
tile_block.cpp:82:35: error: no matching function for call to ‘Map::loop_through_limit(TileBlock::write(Map&, TileBlock::Patterns, int, int, int, int)::<lambda(Tile*)>, int&, int&, int&, int&)’
tile_block.cpp:82:35: note: candidate is:
map.h:26:10: note: void Map::loop_through_limit(Tile* (*)(Tile*), int, int, int, int)
map.h:26:10: note: no known conversion for argument 1 from ‘TileBlock::write(Map&, TileBlock::Patterns, int, int, int, int)::<lambda(Tile*)>’ to ‘Tile* (*)(Tile*)’
我相信当我开始使用我试图通过引用捕获的参数时,问题就出现了。然后它开始变成一个“lambda”函数而不仅仅是一个“函数指针”,也许我只是不明白。
有什么建议么?