十年網站開發(fā)經驗 + 多家企業(yè)客戶 + 靠譜的建站團隊
量身定制 + 運營維護+專業(yè)推廣+無憂售后,網站問題一站解決
目錄
任意函數(shù)對象
備忘
任意類
備忘
總結
#include#include#include#include#include
using namespace std;
templateconcept VoidType = is_void::value;
templateconcept NoneVoidType = !is_void::value;
class BaseService
{
public:
virtual ~BaseService() {}
string info;
};
//question: NoneVoidType and VoidType can not used at the mean time
templateclass Service : public BaseService
{
using FuncType = function;
public:
Service(FuncType func)
:func_(func)
{
}
RetType Run(ArgTypes&&... args)
{
return func_(forward(args)...);
}
private:
FuncType func_;
};
//可變參數(shù)無法偏特化
//template//class Service: public BaseService
//{
// using FuncType = function;
//public:
// Service(FuncType func)
// :func_(func)
// {
//
// }
// void Run(ArgTypes... args)
// {
// func_(args...);
// }
//private:
// FuncType func_;
//};
class ServiceManager
{
using BaseServicePtr = shared_ptr ;
public:
templatevoid RegisterService(const string& name, const ServiceType& service)
{
service_map_.insert(pair(name, BaseServicePtr(new ServiceType(service))));
};
templateRetType Excute(const string& name, ArgTypes&&... args)//
{
if (service_map_.count(name))
{
auto service_ptr = service_map_[name];
Service* true_service_ptr = dynamic_cast*>(service_ptr.get());
return true_service_ptr->Run(forward(args)...);
}
else
{
return RetType();
}
}
private:
unordered_mapservice_map_;
};
struct StatusCode
{
int code = 0;
};
ostream& operator<<(ostream& os, const StatusCode code)
{
os<< "status code: "<< code.code<< endl;
return os;
}
int main()
{
ServiceManager manager;
auto add = [](int a, double b, double& c)->double
{
c = a + b;
return a + b;
};
auto add1 = [](int a, double b, double& c)->StatusCode
{
c = a + b;
return StatusCode{ 0 };
};
Serviceadd_service(add);
Serviceadd1_service(add1);
manager.RegisterService>("add", add_service);
manager.RegisterService>("add1", add1_service);
double test = 0;
cout<("add", 2, 1.08,test)<("add1", 2, 2.08, test);
cout<< test<< endl;
//any a = 2;
//any b = 1.08;
//any c = 0.f;
//any d = a + b;
//cout<< manager.Excute("add", a, b, c)<< endl;
//cout<< any_cast(c)<< endl;
return 0;
}
備忘&& 加 forward完美轉發(fā);
有返回值和無返回值函數(shù)沒辦法用一個類實現(xiàn),通過額外信息記錄。
任意類class A {
public:
static A* Create() { return new A(); }
};
Instance::Register("A", A::Create);
auto a = Instance::Create("A");
備忘c++ 無法存儲類型,只能存儲產生該類型對象的函數(shù);
總結c++ 沒有反射系統(tǒng),在rpc等場景中需要構建用戶級反射系統(tǒng),以便于存儲類型或者函數(shù)。
你是否還在尋找穩(wěn)定的海外服務器提供商?創(chuàng)新互聯(lián)www.cdcxhl.cn海外機房具備T級流量清洗系統(tǒng)配攻擊溯源,準確流量調度確保服務器高可用性,企業(yè)級服務器適合批量采購,新人活動首月15元起,快前往官網查看詳情吧