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.