C++模板,分配“静态”和“动态”对象的问题2

问题描述:

今天我的第二个问题与第一个问题类似。这段代码有什么问题?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个错误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

你的专业化创建的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