今天我的第二個問題與第一個問題類似。這段代碼有什麼問題?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
好的,謝謝。但是我怎麼能得到一種尖銳物體? *項目::類型是不允許的... – Robo 2011-04-02 21:00:56
更新!我認爲這是一個衆所周知的模式,但我不知道這個名字... – Errata 2011-04-02 21:08:55
謝謝,它看起來很有趣... – Robo 2011-04-02 21:09:08