关闭

C++ RTTI使用

263人阅读 评论(0) 收藏 举报
分类:

RTTI.h

#ifndef _RTTI_H_
#define _RTTI_H_
#include <typeinfo>

template<typename T>
class RTTIInfo
{
public:
	RTTIInfo()
	{
		typeName = typeid(T).name();
		hashTypeName = typeid(T).hash_code();
	}

	const char* toString()
	{
		return typeName;
	}

	std::size_t toHashCode()
	{
		return hashTypeName;
	}


private:
	const char* typeName;
	std::size_t hashTypeName;
};

template <typename Parent, typename Children>
class RTTIEx
{
public:
	RTTIEx()
	{
		typeName = typeid(Children).name();
		hashTypeName = typeid(Children).hash_code();
	}

	const char* toString()
	{
		return typeName;
	}

	std::size_t toHashCode()
	{
		return hashTypeName;
	}


private:
	const char* typeName;
	std::size_t hashTypeName;
	std::size_t parentHashCode;
};

#define RTTI_NORMAL_CLASS_FUNCTION(TypeName)\
	const char* toString(){\
		return TypeName::info.toString();\
	}\
	std::size_t toHashCode(){\
		return TypeName::info.toHashCode();\
	}

#define RTTI_ROOT(TypeName)\
	static RTTIInfo<TypeName> info;

#define RTTI_ROOT_IMPL(TypeName)\
	RTTIInfo<TypeName> TypeName::info;

#define RTTI_CHILDREN(Parent, Children)\
	static RTTIEx<Parent,Children> info;

#define RTTI_CHILDREN_IMPL(Parent, Children)\
	RTTIEx<Parent,Children> Children::info;


#endif
fooEx.h

#pragma once
#include "RTTI.h"

class foo
{

public:
	RTTI_ROOT(foo)
	
	foo();
	~foo();
	RTTI_NORMAL_CLASS_FUNCTION(foo)
};


class fooEx:public foo
{

public:
	RTTI_CHILDREN(foo, fooEx)

	fooEx(){}
	~fooEx(){}
	RTTI_NORMAL_CLASS_FUNCTION(fooEx)
};

fooEx.cpp

#include "fooEx.h"


RTTI_ROOT_IMPL(foo)
foo::foo()
{}

foo::~foo()
{

}

RTTI_CHILDREN_IMPL(foo,fooEx)
#include <iostream>
#include "fooEx.h"



int main(int argc,char* argv[])
{
	foo parent;
	fooEx a;

	std::cout << parent.toString() << std::endl;
	std::cout << parent.toHashCode() << std::endl;

	std::cout << foo::info.toString() << std::endl;
	std::cout << foo::info.toHashCode() << std::endl;

	std::cout << a.toString() << std::endl;
	std::cout << a.toHashCode() << std::endl;

	std::cout << fooEx::info.toString() << std::endl;
	std::cout << fooEx::info.toHashCode() << std::endl;

	return  0;
}

源码下载:



附上一个c++ non-intrusive RTTI library

https://github.com/DummySphere/cpp-rtti



0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:1830520次
    • 积分:26087
    • 等级:
    • 排名:第235名
    • 原创:784篇
    • 转载:383篇
    • 译文:0篇
    • 评论:227条
    我的技术博客
    最新评论