在模板中调用对象的方法

Call object's method within template

本文关键字:对象 方法 调用      更新时间:2023-10-16

我有以下代码:

template<class T>
class TemplateA  : public virtual std::list<T>
{
protected:
    unsigned int iSize;
public:
    unsigned int getSize();
};
/////////////
template<class T>
unsigned int TemplateA<T>::getSize()
{
    return iSize;
}
/////////////
/////////////
/////////////
template<class T>
class TemplateB : public TemplateA<T>
{
public:
    unsigned int calcSize();
};
/////////////
template<class C>
unsigned int TemplateB<C>::calcSize()
{
    iSize = C.getSize;
    return iSize;
}
/////////////
/////////////
/////////////
// Class C (seperate file) has to contain function getSize()
class CMyClass
{
public:
    static const unsigned int getSize = 5;
};

这意味着,在类 TemplateB 中,我想调用传递的类定义的 getSize 方法。

我收到以下错误消息:

error C2275: 'C' : illegal use of this type as an expression
while compiling class template member function 'unsigned int TemplateB<C>::calcSize()'
1>          with
1>          [
1>              C=CMyClass
1>          ]

我很确定这个函数在 VS 2003 下工作......方法有什么问题?也许是编译器设置?我不知道在哪里设置什么:(

你应该

this->getSizeC::getSize; 当模板参数已知时,这会将查找推迟到第二阶段。

嗨,

您也可以在更正时简化代码,您似乎所做的只是使用 C 而不是 TemplateB,所以如果您这样做:

template<class C>
unsigned int TemplateB<C>::calcSize()
{
    return  c::getSize; //based on getSize being static
}

您将保存一个额外变量的内存,它应该可以正常工作:)

补遗:下面是一个以代码为基础的工作代码片段:

#include <iostream>
#include <list>
using namespace std;
template<class T>
class TemplateA  : public virtual std::list<T>
{
protected:
    unsigned int iSize;
public:
    unsigned int getSize();
};
template<class T>
unsigned int TemplateA<T>::getSize()
{
    return iSize;
}
template<class T>
class TemplateB : public TemplateA<T>
{
public:
    unsigned int calcSize();
};
template<class C>
unsigned int TemplateB<C>::calcSize()
{
    return C::getSize;
}
// Class C (seperate file) has to contain function getSize()
class CMyClass
{
public:
    static const unsigned int getSize = 5;
};
int main()
{
    CMyClass classme;
    TemplateB<CMyClass> test ;
    cout <<"Calc size outputs: "<< test.calcSize() << endl;
   return 0;
}

对于之前未检查的答案,我们深表歉意。希望这个有帮助!