资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

c++存储任意类型的函数对象和类-创新互联

目录

创新互联公司公司2013年成立,是专业互联网技术服务公司,拥有项目网站建设、成都网站设计网站策划,项目实施与项目整合能力。我们以让每一个梦想脱颖而出为使命,1280元福海做网站,已为上家服务,为福海各地企业和个人服务,联系电话:028-86922220

任意函数对象

备忘

任意类

备忘

总结


任意函数对象
#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_;
};

//可变参数无法偏特化
//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完美转发;

有返回值和无返回值函数没办法用一个类实现,通过额外信息记录。

任意类
class A {
public:
    static A* Create() { return new A(); }
}; 

Instance::Register("A", A::Create);
auto a = Instance::Create("A");
备忘

c++ 无法存储类型,只能存储产生该类型对象的函数;

总结

c++ 没有反射系统,在rpc等场景中需要构建用户级反射系统,以便于存储类型或者函数。

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


新闻名称:c++存储任意类型的函数对象和类-创新互联
转载来于:http://cdkjz.cn/article/hdjhe.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220