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

时间:2011-04-02 20:19:46

标签: c++ templates

我今天的第二个问题与第一个问题类似。这段代码有什么问题?

#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 

2 个答案:

答案 0 :(得分:1)

您的专精化会创建vector Item,但其operator[]会尝试返回Item*

更改operator[]以返回Item&

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

或实际返回Item*,就像签名所说的那样:

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

答案 1 :(得分:1)

错误1错误C2825:'Item':后跟'::

时必须是类或命名空间

此处Item ='Sample *'=&gt;这是一个指针,无论它指向什么,指针仍然是一个包含内存地址的普通旧整数,并且没有像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;
    }
};