C++ operator overloading

Wikipedia is a great source for C++ operator overloading. Well, that sounds strange, but in fact, this page lists exactly what I was looking for. I wasn't able to find any complete reference to what kind of returns etc you need to get a specific operator to work like usually.

Speaking of this, I found a strange problem I strife to solve interesting and resusable. As I like to generalize stuff, I created a nonredundante list for my project, which takes a class T as template parameter and creates a member of this type in each list item. Problem, it's not a pointer, it's directly inside the item class. So if you want to append an item, you'll need to pass a complete T variable (not a pointer) to fill the item's content. And since the class is non-redundant, it compares it's items' data with the == operator. So here's the first problem: You want to pass a structures that's also pointer-heavy inside, but you don't recreate it everytime when you need to copy to the list item. Of course, why don't use a pointer as template parameter? Well, the == operator compares the pointer adresse, not it's content. So there's a problem we can't solve without some rather hacky tricks or simply by copying the whole structure all the time. As I use the class for strings which would require around three times copying with rather expensive comparison, I got the idea of some kind of pointer that free's the data it is pointing at while defining operators to compare it's own content with other class of the same type the pointer is pointing at. So we can dynamically allocate our string class, put it's adresse into this special pointer and make a list of them. We don't need to copy the whole string, only the pointer object. Plus, we can also savely clear the list and free it's content with no previous, unnecessary copying. Nice idea, eh? That solves some problems with template classes and functions, as it's often necessary to store lists with larger objects that just simple integers. I found inspiration in some older memories about early linux classes and links to files that not only delete the link to the original file, but also the orignal file itself. Reflecting which operators are listed on Wikipedia, I think one could design some interesting concepts also incorporating functions and functions pointers. I'm not exactly sure what such a thing would look like but atleast I can make a generic physical link for normal classes and structures that that just link all possible operators to the original data object. Inserted inline, it's only a simple NULL check instead of an otherwise horribly slow copy operation.

However, this solves some design problems I also had to struggle with in the past. Hooray for operator overloading!

No comments: