if else语句的优化
flyfish
假设假设类A的成员函数Process处理的type比较多,if else语句就比较多
void A::Process(int type, std::string s)
{
if (type == 1)
{
Function1(s);
}
else if (type == 2)
{
Function2(s);
}
else if (type == 3)
{
Function3(s);
}
}
优化为类似MFC的消息映射
头文件
class A
{
enum Type
{
Type1,
Type2,
};
typedef void (A::*pFun)(std::string s);
void Function1(std::string s);
void Function2(std::string s);
void CustomMessageMap();
std::map<int, pFun> m_pMessageMap;
void ProcessCustomMessage(int type, std::string s);
};
实现文件
void A::CustomMessageMap()
{
m_pMessageMap.insert(std::make_pair(A::Type1, &A::Function1));
m_pMessageMap.insert(std::make_pair(A::Type2, &A::Function2));
}
void A::Function1(std::string s)
{}
void A::Function2(std::string s)
{}
void A::ProcessCustomMessage(int type, std::string s)
{
auto it = m_pMessageMap.find(type);
if (it != m_pMessageMap.end())
{
(this->*(it->second))(s);
}
}