我加入该响应只是为了显示如何能够在std::bitset
可以用于此目的。我知道,也许你的目标平台不支持C++ 11标准,但希望这可以帮助别人。
g++ locations.cpp -std=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();
}
}
我使用GCC 4.7.2使用以下命令编译它在OS X
action 1
action 2
action 3
action 4
如果只有那些布尔之一将是真实的,你可以连续做四个if语句,而且不需要嵌套。例如,'if(left)doSomething(1);如果(右)doSomething(2);'等等 – Xynariz
什么决定了你的bool的价值?你的测试看起来不寻常左右两边怎么都是真的?对这些变量实际意义的解释可能会有所帮助。 –
我发现想法右边界由左,上和下表示,都是非常直观的。 –