【发布时间】:2015-11-20 00:32:04
【问题描述】:
这个问题是我上一个问题的后续问题
Get type of the parameter, templates, C++
有如下数据结构:
Object1.h
template <class T>
class Object1
{
private:
T a1;
T a2;
public:
T getA1() {return a1;}
typedef T type;
};
Object2.h
template <class T>
class Object2: public Object1 <T>
{
private:
T b1;
T b2;
public:
T getB1() {return b1;}
}
列表.h
template <typename Item>
struct TList
{
typedef std::vector <Item> Type;
};
template <typename Item>
class List
{
private:
typename TList <Item>::Type items;
public:
Item & operator [] ( const unsigned int index ) {return this->items[index];}
};
有没有办法从对象列表中获取对象的类型T(即对象不是函数的直接参数而是模板参数)?
进程.h
class Process
{
template <class Object>
static void process (List <Object> *objects)
{
typename Object::type a1 = (*objects[0]).getA1(); // g++ error: 'Object1<double>*' is not a class, struct, or union type
}
};
但是他的构造是有效的(即Object代表函数的一个参数)
template <class Object>
void process (Object *o1)
{
typename Object::type a1 = (*o1).getA1(); // OK
}
有主程序:
int main()
{
Object1 <double> o1;
Object1 <double> o1;
List <Object1 <double> > list;
Process::process(&list);
}
【问题讨论】:
-
看起来不错。我不知道你为什么会出错。
-
对了,
List类模板是怎么实例化的?你传递什么类型的参数? -
能否请您发布您实际尝试编译的代码?
process(List<Object> *objects)中的objects[0].getA1()正在调用不存在的List<T>::getA1(),并且错误消息引用了在任何地方都没有提及的Object1<double>*。更不用说o1.getA1()不能工作,因为o1是一个指针。 -
为什么不通过引用传递?
-
错误在这里。我写了静态 void 进程(List