type of if statement used for operator overloading?

Jonathan M Davis jmdavisProg at gmx.com
Tue Feb 5 23:52:43 PST 2013


On Wednesday, February 06, 2013 08:41:14 Jeremy DeHaan wrote:
> Out of curiosity, what exactly happens when we don't constrain
> what operators are being overloaded? Is it undefined behavior or
> will the program just not compile?

With no template constraint, a template will match anything with the right 
function arguments, meaning that if you have multiple templates with the same 
signature, they'll conflict, so you'll get a compilation error. So, for 
instance, if you had multple opBinary functions, and they didn't have template 
constraints to distinguish them, then you'd get an error. If you only have one 
of them and you didn't give a template constraint, then you won't get a 
conflict, but you'll get nasty error messages which point to the inside of your 
function when someone tries to use it with bad arguments. It's like what you'd 
be seeing in C++ (which is known for it's horrible template errors). However, 
even if you're not overloading a templated function, putting a template 
constraint on it makes it so that the compiler can give a much more user-
friendly message when someone tries to compile it with bad arguments. It also 
makes it so that the function's body can assume that the condition in the 
template constraint is true, which can make it cleaner and makes it clearer 
what arguments it accepts. In addition, you can overload on template 
constraints, which can be quite powerful (e.g. std.algorithm does this heavily 
with functions such as find). However, you have to be careful to make sure that 
only one template matches any given set of arguments, which can make the 
template constraints much more complicated when you have a lot of overloads.

> And that is a cool use of mixins. They are still a pretty new
> concept to me so I haven't looked into them much.

They're one of the main reasons that D overloads operators the way that it 
does.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list