编译期类型检测与处理

编译期类型检测与处理

简单形式

#include <iostream>
#include <string>
#include <type_traits>
using namespace std;
template<typename T>
constexpr size_t typeJudgeHelper()
{
constexpr size_t t = 1;
constexpr size_t f = 0;
if constexpr (is_same_v<std::string, T>)
{
return f;
}
else if (is_same_v<int, T>)
{
return f;
}
else if (is_same_v<double, T>)
return f;
else
return t;
}

template<typename T>
void typeProcess()
{
if constexpr (is_same_v<std::string, T>)
{
cout << "string" << endl;
}
else if (is_same_v<int, T>)
{
cout << "int" << endl;
}

}

template<typename... Args>
auto TypeSplicing(Args&&...args)
{
// 检测是否存在允许处理的类型
constexpr size_t failsNum = (typeJudgeHelper<Args>() + ...);
static_assert(failsNum == 0);

// 对不同的类型进行处理
(typeProcess<Args>() , ...);
}

int main()
{
TypeSplicing(std::string(""), 1);
return 0;
}

开闭原则

#include <type_traits>
#include <iostream>
using std::cout;
using std::is_same_v;
using std::endl;
namespace autoType
{
template<typename T, typename Tn>
constexpr size_t sameTCouter() // 将is_same_v转换为计数方式
{
if constexpr (is_same_v<Tn, T>)
{
return size_t{ 1 };
}
else
return size_t{ 0 };
}

template<typename ...Types>
class autoTyper {
private:
template<typename T>
void typeDect()
{
constexpr size_t successNum = (sameTCouter<T, Types>() + ...);
static_assert(successNum == 1);
}
template<typename T>
void processer()
{
cout << "int" << endl;
}
public:
// 提交对应的类型处理函数
template<typename T,typename Func>
void submitFunction(Func&& func)
{
// 类型检测
typeDect<T>();
}

// process
template<typename T>
void processType()
{
// 类型检测
typeDect<T>();
// 类型处理
processer<T>();
}
private:
using task = void(*)();
//std::unordered_map<,task> functions;
};
}





int main()
{
autoType::autoTyper<int, double> t;
t.processType<int>();
}