Jump to content
  • Advertisement
Sign in to follow this  
AshleysBrain

C++ templates and part specialization

This topic is 4119 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Advertisement
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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!