views:

125

answers:

3

I have this:

typedef string domanin_name;

And then, I try to overload the operator< in this way:

bool operator<(const domain_name & left, const domain_name & right){
    int pos_label_left = left.find_last_of('.');   
    int pos_label_right = right.find_last_of('.');

    string label_left = left.substr(pos_label_left);
    string label_right = right.substr(pos_label_right);
    int last_pos_label_left=0, last_pos_label_right=0;

    while(pos_label_left!=string::npos && pos_label_right!=string::npos){
        if(label_left<label_right) return true;
        else if(label_left>label_right) return false;

        else{
            last_pos_label_left = pos_label_left;
            last_pos_label_right = pos_label_right;

            pos_label_left = left.find_last_of('.', last_pos_label_left);
            pos_label_right = right.find_last_of('.', last_pos_label_left);

            label_left = left.substr(pos_label_left, last_pos_label_left);
            label_right = right.substr(pos_label_right, last_pos_label_right);
        }
    }
}

I know it's a strange way to overload the operator <, but I have to do it this way. It should do what I want. That's not the point.

The problem is that it enter in an infinite loop right in this line:

if(label_left<label_right) return true;

It seems like it's trying to use this overloading function itself to do the comparision, but label_left is a string, not a domain name!

Any suggestion?

+12  A: 

typedef just gives another name for a type. It does not create a distinct type. So in effect, you're overloading operator < for string.

If you want to create a distinct type, then you can try

struct domain_name {
   string data;
   // ...
};

and work with that.

Jesse Beder
+2  A: 

Typedef doesn't work like this. Typedef simply defines an alias for the type - it is still a string. In order to do this, you would need a new type instead. You should do this anyway. Your operator is overloading the comparison operator for all strings.

Stewart
+1  A: 

Your typedef doesn't create a new type. It just creates a new name to refer to the same type as before. Thus, when you use < inside your operator function on two strings, the compiler just uses the same operator it's compiling because the argument types match.

What you may wish to do instead is define an entirely new function:

bool domain_less(domain_name const& left, domain_name const& right);

Then use that function in places that call for a comparison function, such as std::sort. Most of the standard algorithms will use < by default, but allow you to provide your own predicate function instead. You may need to use std::ptr_fun to wrap your function. You can also write your own functor object; it's typical to descend from std::binary_function in that case. (Check out the <functional> header.)

Rob Kennedy