Skip to main content
remove using namespace std;
Source Link
using namespace std;

static const struct OP__ANG__STRING_CONCAT : AngularOperator<stringAngularOperator<std::string, std::string, std::string> {
    std::string operator()(std::string& lhs, std::string& rhs) const override { return lhs + rhs; }
} C{};
using namespace std;

static const struct OP__ANG__STRING_CONCAT : AngularOperator<string, string, string> {
    string operator()(string& lhs, string& rhs) const override { return lhs + rhs; }
} C{};
static const struct OP__ANG__STRING_CONCAT : AngularOperator<std::string, std::string, std::string> {
    std::string operator()(std::string& lhs, std::string& rhs) const override { return lhs + rhs; }
} C{};
Source Link

Operator Overloading Tricks in C++

This method is taken from Syntactic Aspartame. This is my attempt at a generic version.

The goal is to create an operator X <NAME> Y where name is anything, and X, Y, and the return is of any type.

Here is the 'library':

#ifndef COMPUTERSCIENCE_ANGULAR_OPERATOR_H
#define COMPUTERSCIENCE_ANGULAR_OPERATOR_H

template <typename LHS, typename RHS, typename RET> struct AngularOperator;

template <typename LHS, typename RHS, typename RET>
struct InnerAngularOperator {
    const AngularOperator<LHS, RHS, RET>* outer;
    LHS* lhs;
    bool outer_l;

    RET operator>(RHS& rhs) {
        return (outer_l) ? outer->angular_lr(*lhs, rhs) : outer->angular_rr(*lhs, rhs);
    }

    RET operator<(RHS& rhs) {
        return (outer_l) ? outer->angular_ll(*lhs, rhs) : outer->angular_rl(*lhs, rhs);
    }
};

template <typename LHS, typename RHS, typename RET>
struct AngularOperator {
    explicit AngularOperator() { }

    virtual RET operator()(LHS& lhs, RHS& rhs) const = 0;
    virtual RET angular_lr(LHS& lhs, RHS& rhs) const { return operator()(lhs, rhs); }
    virtual RET angular_rr(LHS& lhs, RHS& rhs) const { return operator()(lhs, rhs); }
    virtual RET angular_ll(LHS& lhs, RHS& rhs) const { return operator()(lhs, rhs); }
    virtual RET angular_rl(LHS& lhs, RHS& rhs) const { return operator()(lhs, rhs); }
};

template <typename LHS, typename RHS, typename RET>
InnerAngularOperator<LHS, RHS, RET> operator<(LHS& lhs, const AngularOperator<LHS, RHS, RET>& outer) {
    return {&outer, &lhs, true};
};

template <typename LHS, typename RHS, typename RET>
InnerAngularOperator<LHS, RHS, RET> operator>(LHS& lhs, const AngularOperator<LHS, RHS, RET>& outer) {
    return {&outer, &lhs, false};
};

#endif //COMPUTERSCIENCE_ANGULAR_OPERATOR_H

And here is a simple implementation for string concatenation:

using namespace std;

static const struct OP__ANG__STRING_CONCAT : AngularOperator<string, string, string> {
    string operator()(string& lhs, string& rhs) const override { return lhs + rhs; }
} C{};

And finally the usage of all of this would be:

std::string a = "123", b = "456";
std::string c = a <C> b;
// c == "123456