def _binary_apply(op, leftval, rightval, cast_type, infix=True):
    """
    Applies the binary operator 'op' to 'leftval' and 'rightval'.
    The operands are cast to the type 'cast_type' first.

    Examples
    --------
    >>> _binary_apply("add", "a", "b", "i64", infix=False)
    'add(i64(a), i64(b))'
    >>> _binary_apply("+", "a", "b", "i64")
    '(i64(a) + i64(b))'
    """
    if infix:
        return "({cast_type}({leftval}) {op} {cast_type}({rightval}))".format(
                op=op, leftval=leftval, rightval=rightval, cast_type=cast_type)
    else:
        return "{op}({cast_type}({leftval}), {cast_type}({rightval}))".format(
                op=op, leftval=leftval, rightval=rightval, cast_type=cast_type)