views:

286

answers:

4
template <class M, class A> class C { std::list<M> m_List; ... }

Is the above code possible? I would like to be able to do something similar.

Why I ask is that i get the following error:

Error 1 error C2079: 'std::_List_nod<_Ty,_Alloc>::_Node::_Myval' uses undefined class 'M'   C:\Program Files\Microsoft Visual Studio 9.0\VC\include\list 41
+2  A: 

Yes. This is very common.

As xtofl mentioned, a forward declaration of your parameter would cause a problem at the time of template instantiation, which looks like what the error message is hinting at.

Harper Shelby
A: 

Yes.

It is used a lot by the STL for things like allocators and iterators.

It looks like you are running into some other issue. Perhaps you are missing a template on an out of line method body definition that was first declared in the ... you elided?

Edward Kmett
+1  A: 

This is a very common usage.

You should make sure that the class M that is specified as the template parameter is fully declared before the creation of the first instance of class C. Perhaps you are missing a header file include or perhaps this is a namespace issue.

Joe Corkery
+4  A: 

My guess: you forward declared class M somewhere, and only declared it fully after the template instantiation.

My hint: give your formal template arguments a different name than the actual ones. (i.e. class M)

// template definition file
#include <list>

template< class aM, class aT >
class C {
    std::list<M> m_List;
    ...
};

Example of a bad forward declaration, resulting in the mentioned error:

// bad template usage file causing the aforementioned error
class M;
...
C<M,OtherClass> c; // this would result in your error

class M { double data; };

Example of proper declaration, not resulting in the error:

// better template usage file
class M { double data; }; // or #include the class header
...

C<M,OtherClass> c; // this would have to compile
xtofl
I sense some psychic debugging here.
Adam Rosenfield
How could that work? Now you have a completely undefined template variable in your defnition. This would cause an error *any* time class C was used, unless there were already a definition for class M in place - or have I missed something completely?
Harper Shelby
That's my point: this code is My guess of what's wrong... That wasn't clear, apparently...
xtofl