OVH Cloud OVH Cloud

template et operator

4 réponses
Avatar
JBB
J'ai une classe template representant une chaine de caractere.
(je n'ai pas le droit d'utiliser string)


template <unsigned int N>
class FixString
{

char texte[N+1];
};

j'ai une autre classe me permettant de depiler des trames:

class Trame
{
operator >> (int &);
operator >> (short &);

};

Le but etant de faire: (mon protocole envoi les chiffres sous forme
binaire (accessoirement bigendian) et les textes avec un 0 à la fin)

...
Trame trame;

int champ1;
short champ2;
FixString<10> champ3;
FixString<5> champ4;

trame >> champ1;
trame >> champ2;
trame >> champ3;
trame >> champ4;
...

Mon problème est donc:
comment je defini un operateur >> qui prenne un template comme type
d'operande.

J'imagine que je peux faire:
class Trame
{
operator >> (int &);
operator >> (short &);
operator >> (FixString<10>);
operator >> (FixString<5>);
...
} mais c'est pas super générique

Ne pourrais-je pas plutôt faire
class Trame
{
operator >> (int &);
operator >> (short &);
operator >> (FixString<int N>);
}

4 réponses

Avatar
Fabien LE LEZ
On Mon, 24 Oct 2005 17:09:05 +0200, JBB :

class Trame
{
template <int N> Trame& operator >> (FixString<N>&);


Avatar
JBB
Fabien LE LEZ wrote:
On Mon, 24 Oct 2005 17:09:05 +0200, JBB :

class Trame
{
template <int N> Trame& operator >> (FixString<N>&);



Et est possible de faire une methode template qui ne change qu'en

fonction du type de retour:

ex:
class FixString
{

char texte[N+1];
};



class Trame
{
template<int N>
(FixString<N>)f();

};

J'ai bien peur que non...


Avatar
Fabien LE LEZ
On Wed, 26 Oct 2005 11:54:55 +0200, JBB :

class Trame
{
template<int N>
(FixString<N>)f();


Essaie ça :

template <int N> FixString<N> f();

Par contre, bien évidemment, il faudra spécifier explicitement le
paramètre template lors de l'appel de la fonction.

Avatar
JBB
Fabien LE LEZ wrote:
On Wed, 26 Oct 2005 11:54:55 +0200, JBB :

class Trame
{
template<int N>
(FixString<N>)f();


Essaie ça :

template <int N> FixString<N> f();

Par contre, bien évidemment, il faudra spécifier explicitement le
paramètre template lors de l'appel de la fonction.

A noter qu'il semble que cela ne fonctionne pas avec Visual C++ 6.

J'obtiens une erreur de compilation sur la ligne:

Trame t;
FixString<5> s = t.f<5>();

Par contre cela fonctionne avec Visual Studio .2003. Et avec ma version
de gcc (4.0.0).