Compile time equality test

A

Alan Woodland

Hi,

Can anyone think of a good way of being able to spot the difference
between the two expressions below at compile time:

class foo {
public:
foo operator+(const foo& rhs) const;
};

int main() {
foo a,b,c;

//expr1:
a = b + c;

//expr2:
a = b + b;

//both expr1 and expr2 use the same operator+

return 0;
}

i.e. is there any clever (standard) trick I can use to get the same
behaviour as if I'd overloaded operator+ (or any other binary operator)
on it's two operands being the same object? The compiler must be know,
but I can't work out how to make it tell me. I know there's no way I
could hope to detect aliasing via pointers etc. but this one case would
be really helpful to spot at compile time.

If there were a way to make foo have a template parameter of type int
that gets incremented every time an instance is created (but is supplied
by default somehow) it would be trivial to provide several versions of
operator+, but I can't work out how to do that.

Thanks,
Alan
 
J

Jim Langston

Alan Woodland said:
Hi,

Can anyone think of a good way of being able to spot the difference
between the two expressions below at compile time:

class foo {
public:
foo operator+(const foo& rhs) const;
};

int main() {
foo a,b,c;

//expr1:
a = b + c;

//expr2:
a = b + b;

//both expr1 and expr2 use the same operator+

return 0;
}

i.e. is there any clever (standard) trick I can use to get the same
behaviour as if I'd overloaded operator+ (or any other binary operator)
on it's two operands being the same object? The compiler must be know,
but I can't work out how to make it tell me. I know there's no way I
could hope to detect aliasing via pointers etc. but this one case would
be really helpful to spot at compile time.

If there were a way to make foo have a template parameter of type int
that gets incremented every time an instance is created (but is supplied
by default somehow) it would be trivial to provide several versions of
operator+, but I can't work out how to do that.

Well, all I know is that the *this pointer of both would be the same. I.E.
In operator+
if ( this == &rhs )
would evaluate to true if it was the same instance, but that's run time, not
compile time.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,756
Messages
2,569,540
Members
45,025
Latest member
KetoRushACVFitness

Latest Threads

Top