一、背景
想参考python那种type的写法,传进去一个值,然后判断是否是对应的类型。
a = 1
if isinstance(a, int):
print(True)
但是因为cpp中的类型实在太多了。int,usigned int,long,unsigned long 等. 我目前的想法就是用string名称,指定到对应的分支去判断。
实现common.h:
template<class T>
bool isDigits(const T &str)
{
try {
if ((std::is_same<std::string, T>::value)) {
return true;
}
} catch (const std::exception &e) {
return false;
}
}
template<>
inline bool isDigits(const std::string &str)
{
return str.find_first_not_of("0123456789") == std::string::npos;
}
template<class T>
bool isInteger(const T &n)
{
if ((std::is_same<int, T>::value) || (std::is_same<long, T>::value)
|| (std::is_same<unsigned long, T>::value) || (std::is_same<unsigned int, T>::value)
|| (std::is_same<AlgorithmType, T>::value)
|| (std::is_same<ProcessStatus, T>::value)
) {
return true;
}
return false;
}
template<>
inline bool isInteger(const json &n)
{
return (n.is_number_integer()) || (n.is_number_unsigned());
}
template<class T>
bool isString(const T &n)
{
if ((std::is_same<std::string, T>::value) || (std::is_same<char, T>::value)) {
return true;
}
return false;
}
template<>
inline bool isString(const json &n)
{
return n.is_string();
}
template<typename T>
bool checkAlgorithmTypeArg(const T &value)
{
if (isInteger(value)) {
return true;
}
return false;
}
template<>
inline bool checkAlgorithmTypeArg(const AlgorithmType &value)
{
if ((AlgorithmType::SingleLabelClassification <= value)
&& (value <= AlgorithmType::OCR)) {
printf("------ AlgorithmType ------ \n");
return true;
}
return false;
}
template<typename T>
bool checkProcessStatusArg(const T &value)
{
if (isInteger(value)) {
return true;
}
return false;
}
template<>
inline bool checkProcessStatusArg(const ProcessStatus &value)
{
if ((ProcessStatus::Cancelling <= value)
&& (value <= ProcessStatus::Finished)) {
printf("------ ProcessStatus ------ \n");
return true;
}
return false;
}
template<class T>
bool checkArg(const T &value, const std::string &Type, json &response){
try {
if (Type == "AlgorithmType") {
if (checkAlgorithmTypeArg(value)) {
return true;
}
} else if (Type == "ProcessStatus") {
if (checkProcessStatusArg(value)) {
return true;
}
} else if (Type == "DigitalStr") {
if (isDigits(value)) {
printf("------ DigitalStr ------ \n");
return true;
}
} else if (Type == "Integer") {
if (isInteger(value)) {
printf("------ Integer ------ \n");
return true;
}
} else if (Type == "String") {
if (isString(value)) {
printf("------ String ------ \n");
return true;
}
}
throw std::exception("The request item arg has invalid type!");
} catch (const std::exception &e)
{
response["msg"] = std::string(e.what());
response["code"] = ErrorType::ErrInvalidArg;
return false;
}
};
二、注意
实现模板要注意几个点,也是踩过的坑。
1.尽量申明跟实现写在header文件里,挨在一起。虽然有header跟cpp实现分开写,但是我目前没尝试成功,会报decal错误。
2.使用模板特例化,一样实现在header中,同时挨近原声明,已经原声明中最好不出现任何具体类型相关的操作,例如:+-*/=等,否则会报未定类型某某操作不合法。最后注意使用inline修饰,否则会报Template specialization, multiple defined symbols。
参考url:
1.c++ - Template specialization, multiple defined symbols - Stack Overflow