Using C++ operators
kiselgra opened this issue · 3 comments
In this case the conversion of lispy names to C-compatible ones causes problems:
(include <iostream>)
(struct v2 (decl ((float x) (float y))))
(function operator<< ((#:std:ostream &os) (const v2 &v)) -> #:std:ostream&
(<< os "(" v.x ", " v.y ")")
(return os))
(function main () -> int
(decl ((v2 v { 1 2}))
(<< #:std:cout v #:std:endl)))
Note how the operator-suffix is converted:
#include <iostream>
struct v2
{
float x;
float y;
};
std::ostream& operator__(std::ostream &os, const v2 &v)
{
os << "(" << v.x << ", " << v.y << ")";
return os;
}
int main()
{
v2 v { 1, 2 };
std::cout << v << std::endl;
}
As before, comment is helpful,
(function (comment "operator<<" :prefix "") ((#:std:ostream &os) (const v2 &v)) -> #:std:ostream&
(<< os "(" v.x ", " v.y ")")
(return os))
but the resulting code looks (in this case only a little) messed-up
std::ostream&
operator<<(std::ostream &os, const v2 &v)
{
os << "(" << v.x << ", " << v.y << ")";
return os;
}
As with #63 this could easily be covered by extending comment and providing a macro that generates that comment. I think it would also be reasonable to not transform names starting with operator
when followed by non-alphanumeric characters, only. Might even be more convenient to the user.
By the way @lispbub, I'm surprised to see that comment is even evaluated in this position. That's pretty cool :)
As a short node, the fix is in the renaming process, not with comment.
Note that operator()
is not easily supported since the syntax we went with (in that case) clashes with the reader. We suggest to use
(function |OPERATOR()| ...) ; all caps necessary
Another approach would be to use the more elegantly written
(function (operator) ...)
Semantically this nicely maps to the intended use of the operator and generates the desired output, but the underlying syntax tree is not valid c++.