Search code examples
c++operatorsdnsdsldsel

C++ domain specific embedded language operators


In numerical oriented languages (Matlab, Fortran) range operator and semantics is very handy when working with multidimensional data. For example:

A(i:j,k,:n) // represents two-dimensional slice B(i:j,0:n)  of A at index k

unfortunately C++ does not have range operator (:). of course it can be emulated using range/slice functor, but semantics is less clean than Matlab. I am prototyping matrix/tensor domain language in C++ and am wondering if there any options to reproduce range operator. I still would like to rely on C++/prprocessor framework exclusively.

So far I have looked through boost wave which might be an suitable option.

is there any other means to introduce new non-native operators to C++ DSL?

I know you cannot add new operators.am specifically looking for workaround. One thing I came up (very ugly hack and I do not intend to use):

#define A(r) A[range(((1)?r), ((0)?r))] // assume A overloads []
A(i:j); // abuse ternary operator

Solution

  • A solution that I've used before is to write an external preprocessor that parses the source and replaces any uses of your custom operator with vanilla C++. For your purposes, a : b uses would be replaced with something like a.operator_range_(b), and operator:() declarations with declarations of range_ operator_range_(). In your makefile you then add a rule that preprocesses source files before compiling them. This can be done with relative ease in Perl.

    However, having worked with a similar solution in the past, I do not recommend it. It has the potential to create maintainability and portability issues if you do not remain vigilant of how source is processed and generated.