Bonjour,
Grâce à ce tuto, j'ai su faire un truc que je n'aurais pas su faire avant: faire un tableau d'éléments de type différents.
Voici ma classe:
Code : C++class TEMPLATE
{
private:
union TEMP
{
friend class TEMPLATE;
private:
int Int;
double Double;
char Char;
bool Bool;
public:
TEMP() {}
TEMP(int i) {Int=i;}
TEMP(double d) {Double=d;}
TEMP(char c) {Char=c;}
TEMP(bool b) {Bool=b;}
operator int() {return Int;}
operator double() {return Double;}
operator char() {return Char;}
operator bool() {return Bool;}
};
TEMP *Temp;
TYPE Type;
public:
TEMPLATE() {Temp=new TEMP;}
TEMPLATE(int i) {Temp=new TEMP(i); Type=INT;}
TEMPLATE(double d) {Temp=new TEMP(d); Type=DOUBLE;}
TEMPLATE(char c) {Temp=new TEMP(c); Type=CHAR;}
TEMPLATE(bool b) {Temp=new TEMP(b); Type=BOOL;}
TEMPLATE(const TEMPLATE &Template) {Copier(Template);}
TEMPLATE &operator=(const TEMPLATE &Template) {if (&Template!=this) {Effacer(); Copier(Template);} return (*this);}
~TEMPLATE() {Effacer();}
operator int() {if (Type==INT) return int(*Temp); else return 0;}
operator double() {if(Type==DOUBLE) return double(*Temp); else return 0;}
operator char() {if(Type==CHAR) return char(*Temp); else return 0;}
operator bool() {if(Type==BOOL) return bool(*Temp); else return false;}
TYPE type() {return Type;}
friend void operator<<(void*, TEMPLATE Template) {switch (Template.Type) {case INT: cout << int(Template); break; case DOUBLE: cout << double(Template); break; case CHAR: cout << char(Template); break; case BOOL: cout << bool(Template); break; default: cout << 0; break;}}
private:
void Copier(const TEMPLATE &Template) {Type=Template.Type; Temp=new TEMP(*Template.Temp);};
void Effacer() {delete Temp;}
};
Et mon énumération:
Code : C++enum TYPE {INT, DOUBLE, CHAR, BOOL};
Voici la fonction test:
Code : C++TEMPLATE Fonction(TEMPLATE Template)
{
if (Template.type()==INT)
return (int(Template)+1);
else if (Template.type()==DOUBLE)
return (double(Template)*2);
else if (Template.type()==CHAR)
return (char(char(Template)+2));
else if (Template.type()==BOOL)
return (!bool(Template));
}
Et voici le main:
Code : C++int main()
{
int n=4;
TEMPLATE *Tableau=new TEMPLATE[n];
Tableau[0]=1;
Tableau[1]=3.14159;
Tableau[2]='T';
Tableau[3]=false;
for (int i=0; i<n; ++i)
{
Cout << Fonction(Tableau[i]);
cout << endl;
}
delete[] Tableau;
getch();
}
J'ajoute cela afin que le cout ne sois pas ambigü!
Code : C++void* Cout;
Et comme par magie, la fonction agira différemment sur les éléments!
C'est vraiment génial
Herbiti
Secret (cliquez pour afficher)
Herbiti
|