Re:My Delorean runs Perl
by throwaway080383 on Saturday January 27, 2018 @11:56AM
(#16246887)
Yep, in C++ you can pass in a lambda to create the comparator inline:
std::sort(
myvec.begin(),
myvec.end(),
[](obj& A, obj& b) {
return A.attr < B.attr;
}
);What I'm talking about is arbitrary attributes that might not exist on the base class, resulting in something like:
std::sort(
myvec.begin(),
myvec.end(),
[](obj& A, obj& b) {
int A_attr1= dynamic_cast<Thing1*>(&A)? dynamic_cast<Thing1*>(&A)->attr1
: dynamic_cast<Thing2*>(&A)? dynamic_cast<Thing2*>(&A)->attr1
: -1;
int B_attr1= dynamic_cast<Thing1*>(&B)? dynamic_cast<Thing1*>(&B)->attr1
: dynamic_cast<Thing2*>(&B)? dynamic_cast<Thing2*>(&B)->attr1
: -1;
return A_attr1 < B_attr1;
}
);
and then compare that to @list= sort { ($a->{attr1} // -1) <=> ($b->{attr1} // -1) } @list;
Re:My Delorean runs Perl
by electricslpnsld on Saturday January 27, 2018 @04:48PM
(#16248261)
If you use std::begin and std::end instead of the member functions this will even work with old-school C-style arrays.
.. and Herb Sutter recommends those free functions over the member functions for this reason -- genericity.
Yes, and you can even use the range syntax instead of begin/end.
Here's a file with a few different ways
https://gist.github.com/anonymous/78b4f257e60d55537b36e2e4f3...
Re:My Delorean runs Perl
by brianwawok on Saturday January 27, 2018 @03:54PM
(#16248040)
That is disgusting as a non-C++ programmer
eh, it's not Haskell (or even D for that matter) but C++ has come a long way in the last few years.
With C++ you can even do it over template parameters.
You need reflection if the type of object you're comparing doesn't have that attribute, and only half the subclasses do. You then have to inspect the actual class to see if the attribute exists before you can access it, and the code to do that is so ugly it would take less time to go edit the base class and constructors to give them all the attribute. This is the hassle that perl is avoiding, in the same way that JavaScript would avoid it. Every object is just a collection of attributes and you can access them by name. It's not as efficient as structs or interfaces, but it's very convenient for prototyping.
In Java, sorting objects based on arbitrary criteria doesn't require reflection. Just pass in a Comparator to one of the JDK-supplied sort methods. It's not awkward. I'm not a C++ programmer but I suspect it's similar.