switch case示例
c
enum class ENTestType
{
first = 1,
second,
third,
forth
};
class Test
{
public:
void testFun(ENTestType type)
{
switch (type)
{
case ENTestType::first:
std::cout << "first" << std::endl;
break;
case ENTestType::second:
std::cout << "first" << std::endl;
break;
case ENTestType::third:
std::cout << "third" << std::endl;
break;
case ENTestType::forth:
std::cout << "forth" << std::endl;
break;
default:
break;
}
}
};
int main()
{
auto t = std::make_unique<Test>();
t->testFun(ENTestType::first);
return 0;
}
使用map替代switch:
cpp
class Test
{
public:
Test()
{
_testMap[ENTestType::first] = []{
std::cout << "first" << std::endl;
};
_testMap[ENTestType::second] = []{
std::cout << "second" << std::endl;
};
_testMap[ENTestType::third] = []{
std::cout << "third" << std::endl;
};
_testMap[ENTestType::forth] = []{
std::cout << "forth" << std::endl;
};
}
public:
std::map<ENTestType, std::function<void()>> _testMap;
};
int main()
{
auto t = std::make_unique<Test>();
t->_testMap[ENTestType::first]();
return 0;
}