In the documentation for boost.geometry it states
Note: prefer using x = bg::get:<0>(point1);
(as opposed to x = point1.get<0>();)
I have seen this elsewhere in the boost docs. My question is why? Is this a best-practices thing, a performance thing or some quirk? Is it a general rule or specific to this library?
It's not boost per se, but modern C++ API design.
By not requiring member functions, you can adapt your own classes and even third party library types to work with the boost Api of your choice. (This way you can e.g. make types from a third party library serializable to a Boost Serialization archive).
Also, by making the functions free functions, there is an improved decoupling of dependencies. E.g.: fusion/tuple.hpp
doesn't need to depend on anything IO related, because the streaming operations are free functions, and hence can be declared (and defined) in a separate header: fusion/tuple_io.hpp
.
It also helps encapsulation because by default the free functions aren't friend
s of the host class (and as such are unable to access private members).
free functions can "Do The Right Thing" based on ADL:
using std::swap;
swap(a, b); // will lookup `swap` in the namespaces that declare the parameter types
(several other namespaces are also used for lookup)
Finally, free functions can generically service a group of types, that need not be OO-related (inheritance related). In this way, free functions encourage avoiding duplication of code.
Edit Addressing the question of why you should prefer the non-member syntax, if both exist:
.template
disambiguation in template code (as pointed out by @Simple)Again: it's not boost specific.
std::swap()
as a free functionstd::begin()
and std::end()
as free functionsstd::hash<>
, std::less<>
, std::greater<>
, std::equal_to<>
similarly provide customization points that are not intrusive (but aren't functions of course)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With