Is it possible to make a custom operator so you can do things like this?
if ("Hello, world!" contains "Hello") ...
Note: this is a separate question from "Is it a good idea to..." ;)
There are a couple publicly available tools to help you out. Both use preprocessor code generation to create templates which implement the custom operators. These operators consist of one or more built-in operators in conjunction with an identifier.
Since these aren't actually custom operators, but merely tricks of operator overloading, there are a few caveats:
_
, o
or similarly simple alphanumerics.While I was working on my own library for this purpose (see below) I came across this project. Here is an example of creating an avg
operator:
#define avg BinaryOperatorDefinition(_op_avg, /)
DeclareBinaryOperator(_op_avg)
DeclareOperatorLeftType(_op_avg, /, double);
inline double _op_avg(double l, double r)
{
return (l + r) / 2;
}
BindBinaryOperator(double, _op_avg, /, double, double)
What started as an exercise in pure frivolity became my own take on this problem. Here's a similar example:
template<typename T> class AvgOp {
public:
T operator()(const T& left, const T& right)
{
return (left + right) / 2;
}
};
IDOP_CREATE_LEFT_HANDED(<, _avg_, >, AvgOp)
#define avg <_avg_>