c++简单实现类的反射-创新互联

一个简单的使用宏在预处理阶段实现类反射的功能

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:申请域名、虚拟空间、营销软件、网站建设、常山网站维护、网站推广。1.classFactory 
//classFactory.h

#ifndef CLASSFACTORY_H
#define CLASSFACTORY_H
#include#includeclass Obj
{
public:
	virtual void show() = 0;
	virtual ~Obj() = default;
};


namespace reflect  

{
	//typedef void* (*create_obj)(void);
	using create_obj = Obj* (*) (void);
	class ClassFactory
	{
	public:
		void register_class(const std::string& className, create_obj method);
		Obj* create_class(const std::string& className);
	
	private:
		ClassFactory() = default;
		~ClassFactory() = default;
		ClassFactory(const ClassFactory&) = delete;
		ClassFactory(ClassFactory&&) = delete;
		ClassFactory& operator=(const ClassFactory&) = delete;
		ClassFactory& operator=(ClassFactory&&) = delete;
	public:
		static ClassFactory* get_instance()
		{
			static ClassFactory classFactory;
			return &classFactory;
		}

	private:
		std::mapclassMap_;

	};
}

#endif


//classFactory.cpp

#include "classFactory.h"



void reflect::ClassFactory::register_class(const std::string& className, reflect::create_obj method)
{
	classMap_[className] = method;
}
Obj* reflect::ClassFactory::create_class(const std::string& className)
{
	auto it = classMap_.find(className);
	if (it != classMap_.end())
	{
		return it->second();
	}
	return nullptr;
}
2.classRegister.h 和test.h
//register.h
#ifndef  CLASS_REGISTER_H
#define CLASS_REGISTER_H
#include "classFactory.h"



class ClassRegister
{
public:
	ClassRegister(const std::string& name, reflect::create_obj method)
	{
		reflect::ClassFactory::get_instance()->register_class(name, method);
	}
};

#define REGISTER_CALSS(ClassName)\
	Obj* createObj##ClassName()\
	{								\
		Obj* obj = new ClassName();\
		return obj;					\
	}								\
	ClassRegister classRegister##ClassName(#ClassName, createObj##ClassName)



#endif // ! CLASS_REGISTER_H

//test.h

#ifndef TEST_H
#define TEST_H
#include#include#include "classRegister.h"


class A :public Obj
{
public:
	A() = default;
	~A() = default;
	virtual void show() override;
public:
	std::string name_;
};
REGISTER_CALSS(A);

inline void A::show() 
{
	std::cout<< "I am A"<< std::endl;
}

class B :public Obj
{
public:
	B() = default;
	~B() = default;
	virtual void show() override;
public:
	std::string name_;
};

inline void B::show()
{
	std::cout<< "I am B"<< std::endl;
}

REGISTER_CALSS(B);

#endif

4.main.cpp

#include#include "classFactory.h"
#include "test.h"

int main()
{
	reflect::ClassFactory* factory = reflect::ClassFactory::get_instance();
	Obj* a = factory->create_class("A");
	a->show();
	Obj* b = factory->create_class("B");
	b->show();

	return 0;
}

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


文章题目:c++简单实现类的反射-创新互联
网页URL:http://ybzwz.com/article/csicoh.html