文明 V のマップを作成するアプリケーションがあります。興味深いデザインの選択として、マップをループ処理する関数をいくつか作成することにしました。このようにして、関数ポインターまたはラムダ関数をその関数に渡し、マップ全体を通過して各タイルに何かを行うことができます。この背後にある理由は、私または他の誰かがマップの保存方法を (2D 配列から 2D ベクトルなどに) 変更した場合、コードベース全体ではなく 1 つの関数のみを変更する必要があるということです。
問題は、ここにいくつかのコードがあります。
エラーコード。
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*)’
そして、参照によってキャプチャしようとしているパラメーターの使用を開始すると、問題が発生すると思います。次に、単なる「関数ポインター」ではなく「ラムダ」関数に変わり始めます。おそらく、私はそれを取得していません。
助言がありますか?