Wookai
Wookai

Reputation: 21723

Mix of template and struct

I have a template class defined as follow :

template <class T1, class T2>
class MyClass { };

In this class, I need a struct that contains one member of type T1. How can I do that ?

I tried the following, but it didn't work :

template <class T1, class T2>
class MyClass {
    typedef struct {
        T1 templateMember;
        // rest of members
    } myStruct;

    // rest of class definition
};

EDIT: As requested, I use VS2008 and get the following error :

'MyClass<T1,T2>::myStruct' uses undefined class 'T1' 

Upvotes: 1

Views: 1250

Answers (3)

moswald
moswald

Reputation: 11667

Are you sure this is exactly what you typed?

    template <class T1, class T2>
    class MyClass {
    public:
        typedef struct {
            T1 templateMember;
            // rest of members
        } myStruct;

        // rest of class definition
    };

    MyClass<int, float> c;
    MyClass<int, float>::myStruct ms;

This compiles and works just fine for me in VS2008 SP1. Note that I added the public: so that I could access myStruct, but it does not affect the correctness of the rest of the declaration.

Upvotes: 1

Dewfy
Dewfy

Reputation: 23614

Just remove typedef:

template <class T1, class T2>
class MyClass {
    struct myStruct{
        T1 templateMember;
        // rest of members
    } ;
};

Upvotes: 2

Khaled Alshaya
Khaled Alshaya

Reputation: 96849

template <class T1>
struct myStruct{
    T1 templateMember;
    // rest of members
};

template <class T1, class T2>
class MyClass {

    myStruct<T1> mystruct;

    // rest of class definition
};

Upvotes: 1

Related Questions