我添加此响应只是为了说明如何将 astd::bitset
用于此目的。我知道您的目标平台可能不支持 C++11 标准,但希望这可以帮助其他人。
#include<iostream>
#include<bitset>
#include<vector>
#include<map>
// The location is represented as a set of four bits; we also need a
// comparator so that we can later store them in a map.
using Location = std::bitset<4>;
struct LocationComparator {
bool operator()(const Location& loc1, const Location& loc2) const {
return loc1.to_ulong() < loc2.to_ulong();
}
};
// the callback (handler) has a signature "void callback()"
using Callback = void (*)( );
// the mapping between location and callback is stored in a simple
// std::map
using CallbackMap = std::map<Location, Callback, LocationComparator>;
// we define the fundamental locations
const Location Top ("1000");
const Location Bottom("0100");
const Location Right ("0010");
const Location Left ("0001");
// ... and define some actions (notice the signature corresponds to
// Callback)
void action_1() { std::cout<<"action 1"<<std::endl;}
void action_2() { std::cout<<"action 2"<<std::endl;}
void action_3() { std::cout<<"action 3"<<std::endl;}
void action_4() { std::cout<<"action 4"<<std::endl;}
// ... now create the map between specific locations and actions
// (notice that bitset can perform logical operations)
CallbackMap callbacks = {
{ Top | Right , action_1 },
{ Top | Left , action_2 },
{ Bottom | Right , action_3 },
{ Bottom | Left , action_4 },
};
// an abstract game element has a location, the interaction will
// depend on the defined callbacks
class GameElement {
public:
GameElement(const Location& location)
: m_location(location) { }
void interact() const {
callbacks[m_location]();
}
virtual ~GameElement() { } // so that others can inherit
private:
Location m_location;
};
int main() {
// create a vector of game elements and make them interact according
// to their positions
std::vector<GameElement> elements;
elements.emplace_back(Top | Right);
elements.emplace_back(Top | Left);
elements.emplace_back(Bottom | Right);
elements.emplace_back(Bottom | Left);
for(auto & e : elements) {
e.interact();
}
}
我使用以下命令在 OS X 上使用 GCC 4.7.2 编译它:
g++ locations.cpp -std=c++11
输出是:
action 1
action 2
action 3
action 4