【问题标题】:Call object's method within template在模板中调用对象的方法
【发布时间】:2013-11-04 09:03:09
【问题描述】:

我有以下代码:

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 下可以工作......这个方法有什么问题?也许是编译器设置?我不知道在哪里设置什么:(

【问题讨论】:

  • 顺便说一句,不鼓励从标准容器继承,因为它们(故意)非虚拟析构函数。

标签: c++ visual-studio-2010 templates visual-studio-2003


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

    附录: 这是一个使用您的代码作为基础的工作代码 sn-p:

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

    为之前未经检查的答案道歉。 希望这个有帮助!

    【讨论】:

    • 这段代码完全错误。这里的语言是 C++,而不是某种 C# 或 Java。
    猜你喜欢
    • 2021-02-28
    • 1970-01-01
    • 2010-11-24
    • 2017-06-29
    • 1970-01-01
    • 2016-06-08
    • 2012-12-20
    • 2016-09-05
    • 1970-01-01
    相关资源
    最近更新 更多