Syntaxe des template avec G++
Bonjour,
J'ai une question liée au template avec G++. Je précise mon compilateur, car avec Microsoft Visual Studio 2008, je n'avais aucun problème pour le même code.
J'ai simplifié au maximum mon code pour qu'il soit présentable sur le forum. Mais même avec ce code simplifié, le problème existe bel et bien.
En résumé, je souhaite avec une classe template, qui contient un conteneur STL dont le type spécifié est le type template.
Voici le code:
Code:
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
| #include <map>
#include <string>
#include <iostream>
template <typename T>
class Foo
{
private:
std::map<std::string, T> entries;
public:
void display()
{
for ( std::map<std::string, T>::iterator itEntries = entries.begin() ; itEntries != entries.end() ; ++itEntries )
{
std::cout << "Key: " << itEntries->first << " -> " << itEntries->second << std::endl;
}
}
void add(const std::string& name, T newValue)
{
entries[name] = newValue;
}
};
int main()
{
Foo<int> myIntMap;
myIntMap.add("Value1",42);
myIntMap.display();
} |
La commande pour la compilation:
Citation:
g++ main.cpp -Wall -Werror -o main
Les erreurs:
Citation:
main.cpp: In member function ‘void Foo<T>::display()’:
main.cpp:16: error: expected ‘;’ before ‘itEntries’
main.cpp:16: error: ‘itEntries’ was not declared in this scope
main.cpp: In member function ‘void Foo<T>::display() [with T = int]’:
main.cpp:34: instantiated from here
main.cpp:16: error: dependent-name ‘std::map::iterator’ is parsed as a non-type, but instantiation yields a type
main.cpp:16: note: say ‘typename std::map::iterator’ if a type is meant
Bizarrement, la définition de l'itérateur lui semble invisible à cause du T. Si je remplace T par un int, tout va bien, cela compile.
En ayant lu la dernière phrase de G++, j'ai tenté le code suivant:
Code:
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
| #include <map>
#include <string>
#include <iostream>
template <typename T>
class Foo
{
typename std::map<std::string, T>::iterator FooIterator;
private:
std::map<std::string, T> entries;
public:
void display()
{
for ( FooIterator itEntries = entries.begin() ; itEntries != entries.end() ; ++itEntries )
{
std::cout << "Key: " << itEntries->first << " -> " << itEntries->second << std::endl;
}
}
void add(const std::string& name, T newValue)
{
entries[name] = newValue;
}
};
int main()
{
Foo<int> myIntMap;
myIntMap.add("Value1",42);
myIntMap.display();
} |
Mais le résultat n'en ai pas meilleur.
Pouvez vous m'indiquer la syntaxe correcte afin que ce code compile avec G++ (et avec Microsoft Visual Studio 2008), s'il vous plait.