Quick actions

cmd+k|ctrl+k

Navigation

Languages

Carry Compare

Snippet info

Language

Cpp

Visibility

public

Author

evine

Created

2017-01-15T10:01:40Z

Updated

2017-01-16T06:01:52Z

#include <stdio.h>

#define cmp(arg, cmp_list) ((Carry_Struct<decltype(arg)>(arg) cmp_list).is_true)

template<typename type>
struct Carry_Struct{
    bool is_true;
    type value;
    
    Carry_Struct(type in)
    {
        is_true = true;
        value = in;
    }
};

#define CREATE_COMPARE(syntax)                                              \
template<typename type>                                                     \
Carry_Struct<type> operator syntax (Carry_Struct<type> carry, int compared) \
{                                                                           \
    if(carry.is_true == false) return carry; /*Short circuit*/              \
    if(carry.value syntax compared == false) carry.is_true = false;         \
    return carry;                                                           \
}

CREATE_COMPARE(<)
CREATE_COMPARE(>)
CREATE_COMPARE(<=)
CREATE_COMPARE(>=)
CREATE_COMPARE(==)
CREATE_COMPARE(!=)

// Beware of dragons, != and == must be the last compares, 
// elsewise the precedence will not be left to right as it reqires.
// -- Sample of the C precedence problem:
// cmp(1, == 5 < 10) // this does 5 < 10
// cmp(1, == 1) // And now it does 1 == 1
// true // And that becomes true

int main() {
    for(char i = 0; i < 16; ++i)
    {
        if(cmp(i, > 3 <= 12 != 7)) // Magic
        {
            printf("Pass: %i\n", i);
        }
        else
        {
            printf("Fail: %i\n", i);
        }
    }
    
    return 0;
}
INFO