在模板中调用对象的方法
Call object's method within template
我有以下代码:
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->getSize
或C::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;
}
对于之前未检查的答案,我们深表歉意。希望这个有帮助!
相关文章:
- 使用std::函数映射对象方法
- 正在调用shared_ptr对象方法
- 检查哪个对象调用了另一个对象的对象方法
- 如何在C++中循环访问未知对象方法?
- c++ 替换调用对象方法的宏函数
- 我能否通过将函数实现为类对象方法来避免使用互斥锁
- 我可以制作一个对象方法,如果单独调用,它将自行修改,但如果在复制初始化期间调用,则会返回一个新对象?
- 如何让两个不同的对象方法相互用作参数
- 在创建 c++ 期间调用对象方法
- 扩展中的日期时间对象方法C++问题
- 将对象方法从向量应用于C 的第二个向量中的对象
- 将 C++/CLI 对象指针传递给本机对象方法
- 多态性的面向对象方法
- 将对象方法传递到变量
- C :使用Main中定义的对象方法的函数
- 有关使用矢量迭代器访问对象方法的问题
- 定义可以执行对象方法和独立函数的函数时出现问题
- 调用列表中子对象方法的最佳方法
- main.cpp:(.text+0x8f):对[对象方法]的未定义引用
- cpp 从需要超类对象的函数访问子类对象方法