mardi 28 août 2018

How to define new behavior for the if and else statements in C++

This is my first question on SO, so my apologies if it is poorly composed.

The project I am working on involves a class, let it be myClass, which is similar to a set, and I need to allow the programmer to compare objects of this type in a meaningful way.

What I would like to be able to do is something like this:

myClass a, b;
...
if (a == b)
{
    //execute code where a and b are implicitly used as
    // each of a and b's elements, respectively
}

and have my custom if statement execute the conditional code for each pair of elements from a and b, based on the condition performed on the pair of elements.

Here is a more concrete example:

myClass a = {1, 2}, b = {2, 3};

if (a == b)
    std::cout << a << " equals " << b << std::endl;
else
    std::cout << a << " does not equal " << b << std::endl;

Where the result would be (not necessarily in this order):

1 does not equal 2
2 equals 2
1 does not equal 3
2 does not equal 3

Currently, I have comparison operators overloaded to return a "comparison type" which simply stores the two operands and the comparison function for lazy evaluation. Is there a way to accomplish this custom if/else behavior so that it occurs whenever an if statement receives a parameter of type "comparison type?" Or is it necessary to just define a regular function which accepts an object of this type and a reference to a binary operator function as the conditional code?

I saw this question, but simply defining a conversion to bool will not work in this case. C++ 'overloading' the if() statement

Aucun commentaire:

Enregistrer un commentaire