Skip to main content
gamedev.net
🔒 Locked

default constructing template parameters

Started by billybob 1 reply 250+ views
Original Post
billybob
billybob
I''m having a bit of trouble writing a templated function for my serialization, the vector one looks like
template < class Type, class Alloc >
inline CArchive & operator << (CArchive & Arc, std::list < Type, Alloc > & List)
{
	int Size = List.size();
	Arc << Size;
	if(Arc.m_Mode & ArcStoring)
	{
		for(std::list < Type, Alloc >::iterator i = List.begin(); i != List.end(); ++i)
			Arc << (*i);
	}
	else
	{
		List.clear();
		Type temp;
		for(int i = 0; i < Size; ++i)
		{
			Arc << temp;
			List.push_back(temp);
		}
	}
	return Arc;
}
 
this works great if Type isn''t a pointer. however, my operator << for pointers requires that it be null before passing it in (if its not, it assumes it points to something and calls a Release() function on it). so, basically I need to say Type temp = NULL, but only when its a pointer. I was thinking about some kind of specialization (I''m not sure how to do this though, I''m a template newbie), but I know MSVC6 has problems with template specialization. How do I solve this problem?
SiCrane
SiCrane
As an aside, using operator<< for both serializing and deserializing is pretty evil.

Anyways, as you might have noticed using templates in MSVC 6 is pretty difficult. One way to approach this problem is to use the boost. type traits facility, combined with a few helper functions and a thunk class. I believe you can accomplish the same thing with Loki's type traits class too. Trust me, using someone else's type trait code for MSVC 6 is much less painful that trying to find inputs that don't cause internal compiler errors.

#include <boost/type_traits.hpp>

template <int i>
struct IntType {};

class CArchive {
// whatever

};

template <typename T, class A>
CArchive & Worker(CArchive & a, std::list<T, A>, IntType<false>) {
std::cout << "Non Pointer" << std::endl;
return a;
}

template <typename T, class A>
CArchive & Worker(CArchive & a, std::list<T, A>, IntType<true>) {
std::cout << "Pointer" << std::endl;
return a;
}

template <typename T, class A>
CArchive & operator<<(CArchive & a, std::list<T, A> & list) {
return Worker(a, list, IntType<::boost::is_pointer<T>::value>());
}

int main() {
CArchive a;
std::list<int> l1;
std::list<int *> l2;
a << l1;
a << l2;

return 0;
}


edit: bad link

[edited by - SiCrane on December 31, 2003 4:56:30 AM]
billybob
billybob
works awsome, thanks. about the aside, I was originally using operator << for serialize and operator >> for deserialize (like MFC), but then I came up with the system for having one of them do both, and I picked operator <<.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.