Forward declaring standard library classes
Jonathan Wakely
cow@compsoc.man.ac.uk
Fri Nov 19 09:50:00 GMT 2004
On Thu, Nov 18, 2004 at 10:05:34PM +0000, Chris Jefferson wrote:
> However, I don't want to pull in <vector>, <list>, <deque>, <map>,
> etc... so I forward declare these classes. However, the following
> doesn't compile:
>
> ***
> #include<functional>
>
> namespace std
> {
> template<typename _Tp>
> class allocator;
> template<class _Key, class _Compare = less<_Key>,
> class _Alloc = allocator<_Key> >
> class set;
> }
>
> #include<set>
> ***
>
> complaining that I have redefined the default parameter to _Compare. It
> (unsuprisingly) doesn't work with my original version, where I also
> forward declare less.
>
> At the moment I'm getting around this by simply including every standard
> container in stl_algo.h, but obviously this cannot continue. Any
> suggestions?
If you forward declare the templates then the default parameters must
only appear on the initial forward declaration. Look at how it's done
with bits/stringfwd.h and bits/basic_string.h
You could have a vectorfwd.h header that can be used by stl_algo.h and
is included at the top of vector. This would make the name "std::vector"
visible (but not usable) when <algorithm> is included (and similarly for
all other types you do this for), which may not be acceptable.
How about having an stl_algo_hasswap.h header that contains just:
template<typename _Tp>
struct _UseSwap
{ enum{_M_type = 0};};
which is enough for it to be used in stl_algo.h
Then in vector include stl_algo_hasswap.h and add a specialisation:
template<typename _Tp>
struct _UseSwap<std::vector<_Tp> >
{enum{_M_type = 1};};
and similarly in map. include stl_algo_hasswap.h and specialise:
template<typename _Tp>
struct _UseSwap<std::map<_Tp> >
{enum{_M_type = 1};};
etc. etc.
It's still early and I've only just had some coffee, but that should work,
because before anyone can use an algorithm on a vector they have to have
included <vector>, at which point the specialisation is visible and will
be used.
jon
--
"Keep away from people who try to belittle your ambitions. Small people
always do that, but the really great make you feel that you, too, can
become great."
- Mark Twain
More information about the Libstdc++
mailing list