Seems std::get
is just used on tuple class. Why not make it member class of tuple in standard library, any other usages?
The reason get is a non-member function is that if this functionality had been provided as a member function, code where the type depended on a template parameter would have required using the template keyword.
source.
Snippet code when get
is non-member function:
template<class T>
void foo ( tuple<T>& t ) {
get<0>(t) = 10; // get is non-member function
}
and another if get
is member function of tuple:
template<class T>
void foo ( tuple<T>& t ) {
t. template get<0>() = 10; // ugly
}
Which version of get
usage do you prefer ? For me, the first is better.
There is also a much older, less c++11 specific and generally more general version of an answer. (If you are only wondering about the specific case, you don't need to read on).
The general case for free functions is described in this classic DrDobb's article by an absolute C++ guru.
The short n sweet version: If you separate between public interface with access to private members and public interface with access to only the public interface you have a harder separation between a class and operations on that class.
It looks somewhat ugly, decreases helpfulness of most IDEs, but has some profound effects on your code modularity, especially when you embrace the template frenzy of the last std
iterations. Matthias's answer depicts one clear example of this.
A more classic advantage is, that you can provide a set of free functions inside an extra header that a user can include on demand. Now think about interoperation between templated but otherwise completely separate classes A
and B
. You can now tie them together by providing a header like A_B_interop.h
, full of free functions, without switching paradigms. You include that header, the classes become more powerful.
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