meta programming

拜读wuye大神github上的大作cpptemplatetutorial,以C++的模板为基础的元编程入门讲义,收获颇丰,虽然仅是入门,更多的是思维上的拓展

元编程,就是对代码进行操作的编程模式。既然是模版元编程,那么就会有以下优点:

1.使用模板,就可以有代码重用、使用安全、类型安全等好处。

2.利用元编程进行类型识别,STL里也用到这种技术、类型识别完了后就根据不同的类型调用适合的函数,提高了效率

3.运算在编译时完成,不占用运行时间。


模板元编程很好的运用了C++模板特化、偏特化的强大功能,和一些技巧,如模版匹配中的SFINAE、递归模板、整型参数等

另记vczh大神的说法:【类型和值是同一种东西】

小应用:

给类型分配id:

#include <iostream>
using std::cout;
using std::endl;

//--------------------- ID type template-------------//
template <typename T> class TypeToID
{
public:
	static int const ID = -1;
};

template <> class TypeToID <uint8_t>
{
public:
	static int const ID = 0;
};

template <> class TypeToID <uint16_t>
{
public:
	static int const ID = 1;
};

template <> class TypeToID <uint32_t>
{
public:
	static int const ID = 2;
};

template <> class TypeToID <uint64_t>
{
public:
	static int const ID = 3;
};

template <> class TypeToID <float>
{
public:
	static int const ID = 0xF10A7;
};

template <> class TypeToID <void* >
{
public:
	static int const ID = 0x401d;
};


template <typename T> class TypeToID<T *>
{
public:
	typedef T SameAsT;
	static int const ID = 0x80000000;
};

//---------------------  RemovePointer template --------------//
template <typename T> class RemovePointer {}; // prototype
template <typename T> class RemovePointer<T*>
{
public:
	typedef T Result;
};

int main()
{
	cout << "ID of uint8_t: " << TypeToID<uint8_t>::ID << endl;
	cout << "ID of uint16_t: " << TypeToID<uint16_t>::ID << endl;
	cout << "ID of uint32_t: " << TypeToID<uint32_t>::ID << endl;
	cout << "ID of uint64_t: " << TypeToID<uint64_t>::ID << endl;
	cout << "ID of float: " << TypeToID<float>::ID << endl;
	cout << "ID of void*: " << TypeToID<void*>::ID << endl;
	cout << "ID of float*: " << TypeToID<float*>::ID << endl;
	// how clever compiler is !
	cout << TypeToID<TypeToID<float*>::SameAsT>::ID << endl;

	RemovePointer<float *>::Result x = 0.5f;
	cout << x << endl;
}

2元编程实现 斐波那契递归:

// prototype
	template <int Index>
	class MetaFibonacci
	{
	public:
		static int const value = MetaFibonacci<Index-1>::value + MetaFibonacci<Index-2>::value;
	};

	// special exit
	template <> 
	class MetaFibonacci<1>
	{
	public:
		static int const value = 1;
	};

	template <>
	class MetaFibonacci<2>
	{
	public:
		static int const value = 1;
	};

3类型判断条件:

// prototype 
	template <typename T, typename N>
	class Equal
	{
	public:
		static bool const value = false;
	};

	// special type 
	template <typename T>
	class Equal<T, T>
	{
	public:
		static bool const value = true;
	};

	bool x = Equal<int, float>::value;
	bool y = Equal<int, int>::value;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值