Yes! (well, kind of)
There are several publicly available tools to help you. Both use preprocessor code generation to create patterns that implement user-defined operators. These statements consist of one or more built-in statements combined with an identifier.
Since these are not ordinary user statements, but just operator overload tricks, there are a few caveats:
- Macros are evil. If you make a mistake, the compiler will be almost useless to track the problem.
- Even if you get the macro correctly, if there is an error in your use of the operator or in the definition of your operation, the compiler will be a little more useful.
- You must use a valid identifier as part of the statement. If you need a more character operator, you can use
_ , o or similarly simple alphanumeric characters.
While I was working on my own library for this purpose (see below), I came across this project. The following is an example of creating an avg statement:
#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 with the exercise in sheer frivolity was my own solution to 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_>
Key Differences
- CustomOperators supports postfix unary operators
- IdOp templates use links, not pointers, to exclude the use of free storage and enable a complete estimate of the time taken to complete an operation
- IdOp makes it easy to specify multiple operations for the same root identifier
Cogwheel 04 Oct '09 at 2:07 2009-10-04 02:07
source share