#include <functional>
#include <iostream>
#include <typeinfo>
#include <typeindex>
#include <unordered_map>
class Type {
};
class A {
public:
static A* instance = nullptr;
Type GetUint32Type()
{
Type type;
// your businsee
return type;
}
Type GetInt32Type()
{
Type type;
// your businsee
return type;
}
Type* GetInstance()
{
if (instance == nullptr) {
instance = new A();
}
return instance;
}
};
using CreateType = std::function<Type()>;
std::unordered_map<std::type_index, CreateType> g_typeTable =
{
{typeid(uint32_t), std::bind(&A::GetUint32Type, A::GetInstance())},
{typeid(int32_t), std::bind(&A::GetInt32Type, A::GetInstance())}
};
应用场景:使用typeid方法获取类型,根据不同的类型去创建对应的封装。
避免出现大量的if/else