Bonjour,
J'ai un souci et je ne sais pas trop comment m'en sortir. J'aimerais faire un template pour traiter des données. Voici un code minimal ci-dessous.
Cela marche très bien si P est directement une classe. Mais je voudrais aussi pouvoir utiliser P comme un pointeur de classe (voir main).
Comment dois-je ecrire la fonction process pour que ce template fonctionne dans les deux cas ?
Voici l'erreur de compilation :
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 #include <iostream> #include <vector> template<typename T, typename P> class DataProcessor { P mProcessor; std::vector<T> mData; public: void push_back(const T& data) { mData.push_back(data); } void set(const P& processor) { mProcessor = processor; } P& get() { return mProcessor; } void process() { for (typename std::vector<T>::iterator it = mData.begin(); it != mData.end(); ++it) { mProcessor.process(*it); } } }; class PrintData { std::string mPrefix; public: void prefix(std::string prefix) { mPrefix = prefix; } void process(int i) { std::cout<<mPrefix<<" : "<<i<<std::endl; } }; int main() { DataProcessor<int, PrintData> p1; p1.get().prefix("prefix"); p1.push_back(1); p1.push_back(2); p1.push_back(3); p1.process(); PrintData* pdata = new PrintData; pdata->prefix("prefix"); DataProcessor<int, PrintData*> p2; p2.set(pdata); p2.push_back(1); p2.push_back(2); p2.push_back(3); p2.process(); }
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4 $ g++ -o main main.cc main.cc: In member function void DataProcessor<T, P>::process() [with T = int, P = PrintData*]: main.cc:56: instantiated from here main.cc:23: error: request for member process in ((DataProcessor<int, PrintData*>*)this)->DataProcessor<int, PrintData*>::mProcessor, which is of non-class type PrintData*
Partager