switch-case语法中规定 case是不能用字符串来进行case分支的 ,有时候可能项目中会有相关的需求
//common.h
#include <stdint.h>
using namespace std;
namespace common
{
constexpr uint32_t strToHash(const char* str);
uint32_t add(uint32_t a, uint32_t b);
};
constexpr uint32_t common::strToHash(const char* str)
{
uint32_t val(0);
for (int i = 0; str && ('\0' != str[i]); i++)
val = (val << 6) ^ (val >> 26) ^ str[i];
return val;
}
//main.cpp
#include <iostream>
#include <vector>
#include "common.h"
#include <string>
#include <stdio.h>
#define CASE(input,func) \
case common::strToHash(input): \
func; \
break;
void myDebug(string str)
{
cout << str << ",hash值:" << common::strToHash(str.c_str()) << endl;
}
void SwitchByString(string str)
{
if (str.size() == 0)
{
return;
}
const char* input = str.c_str(); //string convert to char *
switch (common::strToHash(input))
{
CASE("0x0002", myDebug("0x0002"))
default:
break;
}
}
int main()
{
SwitchByString("0x0002");
system("pause");
return 0;
}