Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to have a Struct with template with a class

With this code (just a class of test):

typedef unsigned short UInt16;

template<class T>
class CClass
{
public:
    SValue* getNewSValue(void);
private:
    typedef struct {
        T *mValue;
        T *next;
        T *previous;
        UInt16 index;
    } SValue;
};

template<typename T>
SValue* CClass<T>::getNewSValue(void)
{
    return new SValue;
}

I have the following errors:

error C2143: syntax error : missing ';' before '*'

error C4430: missing type specifier - int assumed. Note: C++ does not support default-int

Is it possible to use a Struct within a class? If I declare the struct out of the class the template doesn't see the template T.

like image 603
okami Avatar asked Oct 15 '22 00:10

okami


2 Answers

$9.2/2- The key is the below quote from the C++ Standard03

`A class is considered a completely-defined object type (3.9) (or complete type) at the closing } of the class-specifier. Within the class member-specification, the class is regarded as complete within function bodies, default arguments and constructor ctor-initializers (including such things in nested classes). Otherwise it is regarded as incomplete within its own class member-specification.

Don't know what is UINT16, but the following should work

template<class T> 
class CClass 
{ 
private: 
    typedef struct { 
        T *mValue; 
        T *next; 
        T *previous; 
        short int index;                      // Replacing with int for illustration only
    } SValue; 
public:
    SValue* getNewSValue(void); 
private: 
}; 

EDIT 3: The *** came there trying to make the change BOLD (which I should have deleted anyways)

template<class T> typename CClass<T>::SValue* CClass<T>::getNewSValue(void) 
{ 
    return new SValue; 
}

int main(){
    CClass<int> s;
    s.getNewSValue();
}
like image 151
Chubsdad Avatar answered Nov 15 '22 07:11

Chubsdad


Since the member function definition is in global scope, you need to qualify its return type with CClass:: to refer to the name within class scope. Also, the typename keyword is needed when referring to typenames nested within templates.

template<typename T>
typename CClass<T>::SValue* CClass<T>::getNewSValue(void)

Also, the nested struct is unnamed. Note that in C++, classes and structs have proper names, and a typedef name is not a class name. You will be much better off avoiding the typedef.

struct SValue {
    T *mValue;
    T *next;
    T *previous;
    UInt16 index;
};
like image 21
Potatoswatter Avatar answered Nov 15 '22 07:11

Potatoswatter