gpt4 book ai didi

C++ 模板,对象分配问题 "static"和 "dynamic"2

转载 作者:行者123 更新时间:2023-11-28 03:50:54 26 4
gpt4 key购买 nike

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

#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
};

方法“process”应该能够处理分配有“静态”和“动态”对象的容器......

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 ​​error C2825: 'Item': 后跟 '::时必须是类或命名空间

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

关于C++ 模板,对象分配问题 "static"和 "dynamic"2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5525615/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com