How to forward declare a template class in namespace std?
The problem is not that you can't forward-declare a template class. Yes, you do need to know all of the template parameters and their defaults to be able to forward-declare it correctly:
namespace std {
template<class T, class Allocator = std::allocator<T>>
class list;
}
But to make even such a forward declaration in namespace std
is explicitly prohibited by the standard: the only thing you're allowed to put in std
is a template specialisation, commonly std::less
on a user-defined type. Someone else can cite the relevant text if necessary.
Just #include <list>
and don't worry about it.
Oh, incidentally, any name containing double-underscores is reserved for use by the implementation, so you should use something like TEST_H
instead of __TEST__
. It's not going to generate a warning or an error, but if your program has a clash with an implementation-defined identifier, then it's not guaranteed to compile or run correctly: it's ill-formed. Also prohibited are names beginning with an underscore followed by a capital letter, among others. In general, don't start things with underscores unless you know what magic you're dealing with.
I solved that problem.
I was implementing an OSI Layer (slider window, Level 2) for a network simulation in C++ (Eclipse Juno). I had frames (template <class T>
) and its states (state pattern, forward declaration).
The solution is as follows:
In the *.cpp
file, you must include the Header file that you forward, i.e.
ifndef STATE_H_
#define STATE_H_
#include <stdlib.h>
#include "Frame.h"
template <class T>
class LinkFrame;
using namespace std;
template <class T>
class State {
protected:
LinkFrame<int> *myFrame;
}
Its cpp:
#include "State.h"
#include "Frame.h"
#include "LinkFrame.h"
template <class T>
bool State<T>::replace(Frame<T> *f){
And... another class.
Forward declaration should have complete template arguments list specified.