2011-04-02 91 views
0

今天我的第二個問題與第一個問題類似。這段代碼有什麼問題?C++模板,分配「靜態」和「動態」對象的問題2

#include <vector> 

template <typename Item> 
struct TItemsList 
{ 
    typedef std::vector <Item> Type; 
}; 

容器對象:

template <typename Item> 
class Container 
{ 
    protected: 
      typename TItemsList <Item>::Type items; 
public: 
    Item & operator [] (int index) {return items[index];} 
    ... 
    //Other functions 
}; 

//Specialization 
template <typename Item> 
class Container <Item *> 
{ 
    protected: 
      typename TItemsList <Item>::Type items; 
public: 
    Item * operator [] (int index) {return items[index];} 
    ... 
    //Other functions needs to be specialized 
}; 

的方法「過程」應該能夠分配對象的容器的工作既有「靜態」和「動態」 ......

template <typename T> 
class Sample 
{ 
public: 
    T first; 
    T second; 
    typedef T Type; 
}; 

template <typename Item> 
class Process 
{ 
public: 
    void process (Container <Item> *c) 
    { 
     //Compile errors related to left part of the equation, see bellow, please 
     typename Item::Type var = (*c)[0].first + (*c)[0].second; 

    } 
}; 

第一個選項有效,但第二個選項不可用

int main(int argc, _TCHAR* argv[]) 
{ 
Container <Sample <double> > c1; 
Process <Sample <double> > a1; 
a1.process(&c1); 

//Dynamic allocation does not work 
Container <Sample <double> *> c2; 
Process <Sample <double> *> a2; 
a2.process(&c2); 

} 

如何設計一個類/方法「過程」,以便能夠處理分配了「靜態」和「動態」對象的容器?感謝您的幫助..

Error 1 error C2825: 'Item': must be a class or namespace when followed by ':: 
Error 6 error C2228: left of '.second' must have class/struct/union 
Error 5 error C2228: left of '.first' must have class/struct/union 
Error 3 error C2146: syntax error : missing ';' before identifier 'var' 
Error 4 error C2065: 'var' : undeclared identifier 
Error 2 error C2039: 'Type' : is not a member of '`global 

回答

1

錯誤1個錯誤C2825: '項目':必須是類或命名空間後跟'::

Here Item ='Sample *'=>這是一個指針,無論它的目標是什麼,pointers ter仍然是一個普通的舊整數,它包含一個內存地址,並且沒有像Type一樣的屬性。

類似的東西應該做的伎倆

template <typename T> 
struct traits { 
    typedef typename T::Type Type; 
}; 

template<typename T> 
struct traits<T*> { 
    typedef typename traits<T>::Type Type; 
}; 

template <typename Item> 
class Process 
{ 
public: 
    void process (Container <Item>*c) 
    { 
     typename traits<Item>::Type var; 
    } 
}; 
+0

好的,謝謝。但是我怎麼能得到一種尖銳物體? *項目::類型是不允許的... – Robo 2011-04-02 21:00:56

+0

更新!我認爲這是一個衆所周知的模式,但我不知道這個名字... – Errata 2011-04-02 21:08:55

+0

謝謝,它看起來很有趣... – Robo 2011-04-02 21:09:08

1

你的專業化創建的Item一個vector,但其operator[]試圖返回Item*

要麼改變operator[]返回一個Item&

Item& operator [](int index) { return items[index]; } 

或實際返回Item*像簽名表示將:

Item* operator [](int index) { return &items[index]; } 
+0

沒有與運營商[]沒有問題。這個問題與這個等式的一部分有關:typename Item :: Type var = – Robo 2011-04-02 20:34:27

+0

@Robo:對,'operator []' - 'return items [index];絕對有問題'''返回一個'Item& ,但是操作符被定義爲返回一個'Item *'。你如何期待這個工作? – ildjarn 2011-04-02 21:12:30

+0

對不起,我忽略了它,你是對的。但我的問題與方程的左邊部分有關。但是,謝謝你的幫助和注意... – Robo 2011-04-02 21:25:30