switch case示例
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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
使用map替代switch:
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;
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28