views:

200

answers:

3

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'
+1  A: 
template <class T1>
struct myStruct{
    T1 templateMember;
    // rest of members
};

template <class T1, class T2>
class MyClass {

    myStruct<T1> mystruct;

    // rest of class definition
};
AraK
+2  A: 

Just remove typedef:

template <class T1, class T2>
class MyClass {
    struct myStruct{
        T1 templateMember;
        // rest of members
    } ;
};
Dewfy
Can you please explain why he should remove the typedef? Both look like valid C++ code.
Johannes Schaub - litb
It kind of curios example in question well compiled in g++. But MSVC (it kind of assumption) uses another engine to late names resolve. typedef struct... declares anonymous that cannot be referenced and compiler cannot assume entity it deals. Also compilable example (but not in g++) typedef typename struct { - in this case MSVC exactly knows that deals with struct.Once again - it my assumption
Dewfy
+1  A: 

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.

mos
It's a simplified version of my code. But to make sure, I tried in a separate file, and it works indeed. But not in the "complicated" version. I guess the problem is somewhere else...
Wookai
Which is why we need the non-compiling version.
MSalters