Question

I have following code:

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

This means, within class TemplateB I want to call the getSize method, which the passed class have defined.

I receive the following error message:

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>          ]

I'm quiet sure that this function worked under VS 2003... What's wrong with the method? Maybe a compiler setting? I don't know where to set what :(

Was it helpful?

Solution

You should say this->getSize or C::getSize; this will defer lookup to the second phase when the template arguments are known.

OTHER TIPS

Hi you could simplify your code too whilst correcting, all you seem to have done is use C rather than TemplateB so if you do:

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

You will save the memory of an extra variable and it should work fine:)

Addendum: Here is a working code snippet using your code as a basis:

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

Apologies for the unchecked answer previously. Hope this one helps!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top