IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Langage C++ Discussion :

Spécialisation de fonction template dans une class template


Sujet :

Langage C++

  1. #1
    Candidat au Club
    Profil pro
    Inscrit en
    Janvier 2010
    Messages
    3
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2010
    Messages : 3
    Points : 4
    Points
    4
    Par défaut Spécialisation de fonction template dans une class template
    Bonjour à tous,

    Pour un projet, je dois créer une class qui représente un tableau d'élément. Les élément dans une même instance de la class sont de mêmes types mais il doit pouvoir y avoir 3 types différents dans cette class : Animal, Region, Vivre.
    Certaines fonctions de la class sont communes aux trois type d'objet possible mais certaines non. J'ai donc spécialisé une partie des fonctions.

    3 fonctions ont été surchargé et spécialisé. Pour les 3, j'obtiens une erreur de multiple definition lors du linkage des .o à partir du moment ou j'inclus tableau.hpp dans plus d'un fichier or, il faut que je l'inclus dans 2.

    Merci d'avance à toutes personne pouvant m'éclairer sur ce mystère.

    obj\Debug\requete.o||In function `_ZNK14TableauElementI5VivreE6existeERK6RegionRK6Animal'
    tableau.tpp|323|multiple definition of `TableauElement<Vivre>::existe(Region const&, Animal const&) const'|
    obj\Debug\main.o:tableau.tpp|323|first defined here|
    obj\Debug\requete.o||In function `_ZNK14TableauElementI5VivreE6existeERKSsi'
    tableau.tpp|316|multiple definition of `TableauElement<Vivre>::existe(std::string const&, int) const'|
    obj\Debug\main.o:tableau.tpp|316|first defined here|
    obj\Debug\requete.o||In function `_ZNK14TableauElementI5VivreE7indexOfERK6RegionRK6Animal'
    tableau.tpp|178|multiple definition of `TableauElement<Vivre>::indexOf(Region const&, Animal const&) const'|
    obj\Debug\main.o:tableau.tpp|178|first defined here|
    obj\Debug\requete.o||In function `_ZNK14TableauElementI5VivreE7indexOfERKSsi'
    tableau.tpp|171|multiple definition of `TableauElement<Vivre>::indexOf(std::string const&, int) const'|
    obj\Debug\main.o:tableau.tpp|171|first defined here|
    obj\Debug\requete.o||In function `_ZNK14TableauElementI6RegionE6existeERKSs'
    tableau.tpp|309|multiple definition of `TableauElement<Region>::existe(std::string const&) const'|
    obj\Debug\main.o:tableau.tpp|309|first defined here|
    obj\Debug\requete.o||In function `_ZNK14TableauElementI6AnimalE6existeEi'
    tableau.tpp|285|multiple definition of `TableauElement<Animal>::existe(int) const'|
    obj\Debug\main.o:tableau.tpp|285|first defined here|
    obj\Debug\requete.o||In function `_ZNK14TableauElementI6RegionE7indexOfERKSs'
    tableau.tpp|164|multiple definition of `TableauElement<Region>::indexOf(std::string const&) const'|
    obj\Debug\main.o:tableau.tpp|164|first defined here|
    obj\Debug\requete.o||In function `_ZNK14TableauElementI6AnimalE7indexOfEi'
    tableau.tpp|140|multiple definition of `TableauElement<Animal>::indexOf(int) const'|
    obj\Debug\main.o:tableau.tpp|140|first defined here|
    obj\Debug\requete.o||In function `_ZNK14TableauElementI6AnimalE6existeERKSs'
    tableau.tpp|292|multiple definition of `TableauElement<Animal>::existe(std::string const&) const'|
    obj\Debug\main.o:tableau.tpp|292|first defined here|
    obj\Debug\requete.o||In function `_ZNK14TableauElementI6AnimalE7indexOfERKSs'
    tableau.tpp|147|multiple definition of `TableauElement<Animal>::indexOf(std::string const&) const'|
    obj\Debug\main.o:tableau.tpp|147|first defined here|
    obj\Debug\requete.o||In function `_ZN14TableauElementI6AnimalE8supprimeERKSs'
    tableau.tpp|234|multiple definition of `TableauElement<Animal>::supprime(std::string const&)'|
    obj\Debug\main.o:tableau.tpp|234|first defined here|
    obj\Debug\requete.o||In function `_ZN14TableauElementI6AnimalE8supprimeEi'
    tableau.tpp|223|multiple definition of `TableauElement<Animal>::supprime(int)'|
    obj\Debug\main.o:tableau.tpp|223|first defined here|
    obj\Debug\requete.o||In function `_ZN14TableauElementI5VivreE8supprimeERK6RegionRK6Animal'
    tableau.tpp|267|multiple definition of `TableauElement<Vivre>::supprime(Region const&, Animal const&)'|
    obj\Debug\main.o:tableau.tpp|267|first defined here|
    obj\Debug\requete.o||In function `_ZN14TableauElementI5VivreE8supprimeERKSsi'
    tableau.tpp|256|multiple definition of `TableauElement<Vivre>::supprime(std::string const&, int)'|
    obj\Debug\main.o:tableau.tpp|256|first defined here|
    obj\Debug\requete.o||In function `_ZN14TableauElementI6RegionE8supprimeERKSs'
    tableau.tpp|245|multiple definition of `TableauElement<Region>::supprime(std::string const&)'|
    obj\Debug\main.o:tableau.tpp|245|first defined here|
    ||=== Build finished: 30 errors, 0 warnings ===|
    Le code :
    tableau.hpp
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
     
    #ifndef TEMPLATE_TABLEAU_ELEMENT
    #define TEMPLATE_TABLEAU_ELEMENT
     
    #include <iostream>
    #include <string>
     
    #include "vecteur.hpp"
    #include "animal.hpp"
    #include "vivre.hpp"
    #include "region.hpp"
     
    template<typename T>
    class TableauElement
    {
        public :
            TableauElement();
            TableauElement(const TableauElement<T> & other);
            ~TableauElement();
     
            unsigned int getNombreElement() const;
     
            bool ajout(const T & element);
     
            bool existe(const T & element) const;
            //Spécialisation de la fonction existe pour certains types
            ///Pour les animaux
                bool existe(const int refAnimal) const;
            ///Pour les animaux et les régions
                bool existe(const std::string & nom) const;
            ///Pour vivre
                bool existe(const std::string & nomRegion, const int refAnimal) const;
                bool existe(const Region & itemRegion, const Animal & itemAnimal) const;
     
     
            int indexOf(const T & element) const;
            //Spécialisation de la fonction pour certains types
            ///Pour les animaux
                int indexOf(const int refAnimal) const;
            ///Pour les animaux et les régions
                int indexOf(const std::string & nom) const;
            ///Pour vivre
                int indexOf(const std::string & nomRegion, const int refAnimal) const;
                int indexOf(const Region & itemRegion, const Animal & itemAnimal) const;
     
            bool supprime(const T & element);
            //Spécialisation de la fonction supprime pour certains types
            ///Pour les animaux
                bool supprime(const int refAnimal);
            ///Pour les animaux et les régions
                bool supprime(const std::string & nom);
            ///Pour vivre
                bool supprime(const std::string & nomRegion, const int refAnimal);
                bool supprime(const Region & itemRegion, const Animal & itemAnimal);
     
     
            ///Surcharge des opérateurs de lecture et écriture
            T operator[](unsigned int n) const;
            T & operator[](unsigned int n);
     
            ///Surcharge de l'opérateur d'affectation
            TableauElement<T> & operator=(const TableauElement<T> & other);
     
        protected :
            Vecteur<T> *tab;
    };
     
    #include "tableau.tpp"
     
    #endif
    tableau.tpp
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    232
    233
    234
    235
    236
    237
    238
    239
    240
    241
    242
    243
    244
    245
    246
    247
    248
    249
    250
    251
    252
    253
    254
    255
    256
    257
    258
    259
    260
    261
    262
    263
    264
    265
    266
    267
    268
    269
    270
    271
    272
    273
    274
    275
    276
    277
    278
    279
    280
    281
    282
    283
    284
    285
    286
    287
    288
    289
    290
    291
    292
    293
    294
    295
    296
    297
    298
    299
    300
    301
    302
    303
    304
    305
    306
    307
    308
    309
    310
    311
    312
    313
    314
    315
    316
    317
    318
    319
    320
    321
    322
    323
    324
    325
    326
     
    #ifdef TEMPLATE_TABLEAU_ELEMENT
     
    template<typename T>
    TableauElement<T>::TableauElement()
    {
        try
        {
            tab = new Vecteur<T>();
        }
        catch (const std::exception & e)
        {
            throw;
        }
    }
     
    template<typename T>
    TableauElement<T>::TableauElement(const TableauElement<T> & other)
    {
        unsigned int taille = other.getNombreElement();
        if (taille != 0)
        {
            try
            {
                tab = new Vecteur<T>(taille);
            }
            catch (const std::exception & e)
            {
                throw;
            }
            for (int i = 0 ; i < taille ; ++i)
            {
                tab[i] = other[i];
            }
        }
        else
        {
            try
            {
                tab = new Vecteur<T>();
            }
            catch (const std::exception & e)
            {
                throw;
            }
        }
    }
     
    template<typename T>
    TableauElement<T>::~TableauElement()
    {
        delete tab;
    }
     
    template<typename T>
    unsigned int TableauElement<T>::getNombreElement() const
    {
        return tab->size();
    }
     
    template<typename T>
    T TableauElement<T>::operator[](unsigned int n) const
    {
        if (n < tab->size())
            return tab->at(n);
        else
            throw int(-1);
    }
     
    template<typename T>
    T & TableauElement<T>::operator[](unsigned int n)
    {
        if (n < tab->size())
            return tab->at(n);
        else
            throw int(-1);
    }
     
    template<typename T>
    bool TableauElement<T>::existe(const T & element) const
    {
        if (tab->size() == 0)
            return false;
        bool retour = false;
        int min = 0, max = tab->size();
        int courant = (max - min) / 2;
        int precedent = courant-1;
        T e = tab->at(courant);
        while (courant != precedent && element != e)
        {
            if (e < element)
                min = courant;
            else
                max = courant;
     
            precedent = courant;
            courant = ((max - min) / 2) + min;
            e = tab->at(courant);
        }
     
        if (e == element) //Si on a trouvé
            retour = true;
     
        return retour;
    }
     
    template<typename T>
    int TableauElement<T>::indexOf(const T & element) const
    {
        if (tab->size() == 0)
            return -1;
        int retour = -1;
        int min = 0, max = tab->size();
        int courant = (max - min) / 2;
        int precedent = courant-1;
        T e = tab->at(courant);
        while (courant != precedent && element != e)
        {
            if (e < element)
                min = courant;
            else
                max = courant;
     
            precedent = courant;
            courant = ((max - min) / 2) + min;
            e = tab->at(courant);
        }
     
        if (e == element) //Si on a trouvé
            retour = courant;
     
        return retour;
    }
     
    template<typename T>
    bool TableauElement<T>::ajout(const T & element)
    {
        if (existe(element))
            return false;
        tab->ajout(element);
        return true;
     
    }
     
    template<typename T>
    TableauElement<T> & TableauElement<T>::operator=(const TableauElement<T> & other)
    {
        if (this != &other)
        {
            tab->clear();
            int taille = other.getNombreElement();
            tab->setSize(taille);
            for (int i = 0 ; i < taille ; ++i)
            {
                tab[i] = other[i];
            }
        }
        return * this;
    }
     
    template<typename T>
    bool TableauElement<T>::supprime(const T & element)
    {
        int index = indexOf(element);
        if (index != -1)
        {
            tab->erase(index);
            return true;
        }
        return false;
    }
     
    template<>
    bool TableauElement<Animal>::supprime(const int refAnimal)
    {
        int index = indexOf(refAnimal);
        if(index != -1)
        {
            tab->erase(index);
            return true;
        }
        return false;
    }
     
    bool TableauElement<Animal>::supprime(const std::string & nom)
    {
        int index = indexOf(nom);
        if(index != -1)
        {
            tab->erase(index);
            return true;
        }
        return false;
    }
     
    bool TableauElement<Region>::supprime(const std::string & nom)
    {
        int index = indexOf(nom);
        if(index != -1)
        {
            tab->erase(index);
            return true;
        }
        return false;
    }
     
    bool TableauElement<Vivre>::supprime(const std::string & nomRegion, const int refAnimal)
    {
        int index = indexOf(nomRegion, refAnimal);
        if(index != -1)
        {
            tab->erase(index);
            return true;
        }
        return false;
    }
     
    bool TableauElement<Vivre>::supprime(const Region & itemRegion, const Animal & itemAnimal)
    {
        int index = indexOf(itemRegion, itemAnimal);
        if(index != -1)
        {
            tab->erase(index);
            return true;
        }
        return false;
    }
     
    template<typename T>
    int TableauElement<T>::indexOf(const int refAnimal) const
    {
        return -1;
    }
     
    template<>
    int TableauElement<Animal>::indexOf(const int refAnimal) const
    {
        Animal a(refAnimal, "", 7, 0);
        return indexOf(a);
    }
     
    template<>
    int TableauElement<Animal>::indexOf(const std::string & nom) const
    {
        unsigned int taille = tab->size();
        if (taille == 0)
            return -1;
     
        int retour = -1;
     
        for (unsigned int i = 0 ; i < taille && retour == -1 ; i++)
        {
            if (nom == tab->at(i).getNom())
                retour = i;
        }
        return retour;
    }
     
    template<>
    int TableauElement<Region>::indexOf(const std::string & nom) const
    {
        Region r(nom, "", 0, 1);
        return indexOf(r);
    }
     
    template<>
    int TableauElement<Vivre>::indexOf(const std::string & nomRegion, const int refAnimal) const
    {
        Vivre v(refAnimal, nomRegion, 0, false);
        return indexOf(v);
    }
     
    template<>
    int TableauElement<Vivre>::indexOf(const Region & itemRegion, const Animal & itemAnimal) const
    {
        Vivre v(itemAnimal, itemRegion, 0, false);
        return indexOf(v);
    }
     
    template<>
    bool TableauElement<Animal>::existe(const int refAnimal) const
    {
        Animal a(refAnimal, "", 7, 0);
        return existe(a);
    }
     
    template<>
    bool TableauElement<Animal>::existe(const std::string & nom) const
    {
        unsigned int taille = tab->size();
        if (taille == 0)
            return false;
     
        bool retour = false;
     
        for (unsigned int i = 0 ; i < taille && !retour ; i++)
        {
            if (nom == tab->at(i).getNom())
                retour = true;
        }
        return retour;
    }
     
    template<>
    bool TableauElement<Region>::existe(const std::string & nom) const
    {
        Region r(nom, "", 0, 1);
        return existe(r);
    }
     
    template<>
    bool TableauElement<Vivre>::existe(const std::string & nomRegion, const int refAnimal) const
    {
        Vivre v(refAnimal, nomRegion, 0, false);
        return existe(v);
    }
     
    template<>
    bool TableauElement<Vivre>::existe(const Region & itemRegion, const Animal & itemAnimal) const
    {
        Vivre v(itemAnimal, itemRegion, 0, false);
        return existe(v);
    }
     
     
    #endif

  2. #2
    Rédacteur
    Avatar de 3DArchi
    Profil pro
    Inscrit en
    Juin 2008
    Messages
    7 634
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Juin 2008
    Messages : 7 634
    Points : 13 017
    Points
    13 017
    Par défaut
    Bonjour et bienvenu,
    Essaies :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    template<typename T>
    inline TypeRetour TableauElement<T>::ma_fonction(){}

  3. #3
    Membre confirmé Avatar de Lavock
    Profil pro
    Inscrit en
    Octobre 2009
    Messages
    560
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2009
    Messages : 560
    Points : 633
    Points
    633
    Par défaut
    Y a pas un moyen plus "propre" ou on déclare la template sans l'instancier tout de suite ?

    Sinon, ça me semble un peu étrange. Pour avoir des erreurs, tu dois avoir une même instance dans plusieurs unité de compilations. Or elles sont censé être indépendante.

    Problème de conception ?
    The mark of the immature man is that he wants to die nobly for a cause, while the mark of the mature man is that he wants to live humbly for one.
    --Wilhelm Stekel

  4. #4
    Membre confirmé
    Avatar de gb_68
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Août 2006
    Messages
    232
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France, Haut Rhin (Alsace)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2006
    Messages : 232
    Points : 546
    Points
    546
    Par défaut
    Citation Envoyé par Lavock Voir le message
    Y a pas un moyen plus "propre" ou on déclare la template sans l'instancier tout de suite ?
    Quelque chose comme ça ?
    J'avais eu le même souci (Merci à 3DArchi).

  5. #5
    Membre confirmé Avatar de Lavock
    Profil pro
    Inscrit en
    Octobre 2009
    Messages
    560
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Octobre 2009
    Messages : 560
    Points : 633
    Points
    633
    Par défaut
    Je pensais pas à ça, mais plus as une feature C++0x (tiens au faite, toute vanne hexa mis à part, on peut appeler ça c++1x maintenant ?).

    La version "générique" lui vas apparemment, il n'as qu'a instancier. Le problème c'est qu'il le fait dans plusieurs unité de compilation. Et il me sembler que y avait moyen de déclarer une instance sans instancier réellement genre :

    .h
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
     extern template class machin<truc>;
    .cpp
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
     template class machin<truc>;
    The mark of the immature man is that he wants to die nobly for a cause, while the mark of the mature man is that he wants to live humbly for one.
    --Wilhelm Stekel

  6. #6
    Candidat au Club
    Profil pro
    Inscrit en
    Janvier 2010
    Messages
    3
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2010
    Messages : 3
    Points : 4
    Points
    4
    Par défaut
    Merci à tous de vos réponses, j'ai finalement réussi à corriger le problèmes des redéfinition, il fallait en fait mettre les fonctions spécialisé dans un fichier .cpp comme pour n'importe qu'elle class en les faisant précédé de

  7. #7
    Membre confirmé
    Avatar de gb_68
    Homme Profil pro
    Ingénieur développement logiciels
    Inscrit en
    Août 2006
    Messages
    232
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 40
    Localisation : France, Haut Rhin (Alsace)

    Informations professionnelles :
    Activité : Ingénieur développement logiciels
    Secteur : High Tech - Éditeur de logiciels

    Informations forums :
    Inscription : Août 2006
    Messages : 232
    Points : 546
    Points
    546
    Par défaut
    Dans ce cas, attention à bien mettre les prototypes des spécialisations dans le .h (un peu comme dans la solution que m'avait donné 3DArchi, même si il s'agissait là de fonctions membres template - cf lien plus haut).
    Exemple :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    template<>
    bool TableauElement<Animal>::supprime(const int refAnimal);
    Si tu l'oublies, le compilateur risque de la régénérer à partir de la version générique.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. Réponses: 4
    Dernier message: 22/11/2010, 14h15
  2. Réponses: 4
    Dernier message: 20/10/2009, 08h54
  3. Fonction template dans une classe template
    Par mister3957 dans le forum Langage
    Réponses: 9
    Dernier message: 08/07/2008, 12h11
  4. Réponses: 8
    Dernier message: 20/07/2007, 14h28
  5. Réponses: 4
    Dernier message: 08/11/2005, 15h10

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo