Sign in to follow this  
AshleysBrain

C++ templates and part specialization

Recommended Posts

I'm writing my own CArchive-style class which I want to overload the << operators to write various types to a binary memory space in my own format, eg:
myclass& operator<<(int x)
{
	extend(sizeof(int)); // make sure enough room to store
	*((int*)&(data[datasize])) = x; // write the data
	datasize += sizeof(int); // move cursor along
	return *this; // for chaining
}
eg. ar << 5 << 6. Now, if I use a template like so, it saves me writing out every version of this function from unsigned/signed char, short, int, long, __int64, etc.:
template<typename T>
myclass& operator<<(const T& x)
{
	extend(sizeof(T)); // make sure enough room to store
	*((T*)&(data[datasize])) = x; // write the data
	datasize += sizeof(T); // move cursor along
	return *this; // for chaining
}
The problem is if you then do ar << myCString it gets all messed up, with a binary copy of the bits of the CString class, not the string held. I can use a specialization to overcome this specifically for CString, but it makes it more error-prone as it will still happily accept pointers, references, and other user-made classes without any regard for any pointed-to data. Do C++ templates provide a way to say a template for a certain group of types? Like char to __int64s? I've vaguely heard of type traits before, is this the kind of thing they're useful for? Is the best way simply to copy+paste my function multiple times for all the types possible?

Share this post


Link to post
Share on other sites
This is exactly what type-traits is for. The syntax is hideous, but it'll do exactly what you want. This page will get you up to speed.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this