Generic Programming

Hello all. It's nice to meet you all here. I got a lot of knowledge from csdn. now, I try to feed back some. the topic is about Generic Programming.

I paste a snippet to show how it works.
Everyone who has studied the book Think in C++ 2nd Edition knows the sample, trash collection, which is at the end of chapter 10, Design pattern.
Ok, let's begin with this.
the sample mentioned in Think in C++ using double dispatch to implement the design. and I use Generic Programming method to do the same thing.
Enjoy.

#include<vector>
#include <iostream>
using namespace std;
class Trash
{
};
class Paperbin;
class Glassbin;
class Paper:public Trash
{
public:
typedef Paperbin aBin;
};

class Glass:public Trash
{
public:
typedef Glassbin aBin;
};

class Paperbin:public vector<Paper>
{
};
class Glassbin:public vector<Glass>
{
};

template<int v>
struct Int2Type
{
enum{value=v};
};
template<class T, class U>
class Conversion
{
typedef char Small;
struct Big {char dummy[2];
};
static Small Test(U);
static Big Test(...);
static T MakeT();
public:
enum{ exists=(sizeof(Test(MakeT()))==sizeof(Small))};
};
template<class Trashs, class Bin>
Add(Trashs trash, Bin bin)
{
cout<<Conversion<Trashs::aBin ,Bin>::exists<<endl;
_Add(trash,bin,Int2Type<Conversion<Trashs::aBin ,Bin>::exists >());
}

template<class Trash, class Bin>
_Add(Trash trash, Bin bin,Int2Type<true>)
{
bin.push_back(trash);
cout<<"success adding"<<endl;
};
template<class Trash, class Bin>
_Add(Trash trash, Bin bin,Int2Type<false>)
{
cout<<"failed adding"<<endl;
};

int main()
{

Paper apaper;
Glass aglass;
Paperbin apaperbin;
Glassbin aglassbin;
Add(apaper,apaperbin);
Add(aglass,aglassbin);
Add(apaper,aglassbin);
Add(aglass,apaperbin);
return 0;
}

you can reach me by send me a email at bu3bu4@263.net.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值