Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does boost recommend using core functions over member functions?

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?

like image 293
mmdanziger Avatar asked Dec 09 '22 10:12

mmdanziger


1 Answers

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 friends 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:

  • it works for types that don't have the member function
  • it doesn't require .template disambiguation in template code (as pointed out by @Simple)
  • Again: it's not boost specific.

    • c++03 has had std::swap() as a free function
    • c++11 introduces std::begin() and std::end() as free functions
    • std::hash<>, std::less<>, std::greater<>, std::equal_to<> similarly provide customization points that are not intrusive (but aren't functions of course)
like image 153
sehe Avatar answered Feb 03 '23 11:02

sehe