juli (caladri) wrote in dailysrc,
juli
caladri
dailysrc

handling less than, equal to and greater than gracefully

I hate repetetive code, perhaps pathologically so. In particular, I always find myself glaring at:
        if (a < -300) {
                puts("lt\n");
        } else if (a == -300) {
                puts("e\n");
        } else {
                puts("gt\n");
        }

Why should I have to write -300 so many times? This has always bugged me. I was thinking about what I'd like some imagined language syntax to look like for handling this more gracefully and realized that I could do it in C++ with templates as is:
template<typename Ta, typename Tb>
static char
cmp(Ta a, Tb b)
{
        return (a < b ? '<' : a == b ? '=' : '>');
}

Which allows for the perhaps better:
        switch (cmp(a, -300)) {
        case '<':
                puts("lt\n");
                break;
        case '=':
                puts("e\n");
                break;
        case '>':
                puts("gt\n");
                break;
        }

Some trivial testing even suggests that GCC's c++ compiler properly optimizes through the template, getting rid of the character intermediaries which were just there for human eyes in the first place. Cool.
  • Post a new comment

    Error

    default userpic

    Your IP address will be recorded 

  • 0 comments