On Thursday, 23 November 2017 23:44:16 UTC+2, Jorgen Grahn wrote:
> On Thu, 2017-11-23, Öö Tiib wrote:
> > The C++ developers are different and so some write functions as
> > members, others as free functions or templates or even
> > specialize standard library templates.
>
> Of course it also depends on the situation: which function you're
> implementing.
Yes, that is what I meant. It depends on situation what function
with what data and who is implementing. For example different people
think differently what is better: hash(a) or a.hash() ...
a.to_string() or to_string(a) ... a.clone() or clone(a) ... and so on.
>
> > There must be some trick how to sort that out with code.
> >
> > How to implement such function template that calls a member
> > function or if such is not present then function from namespace
> > of argument or from global namespace or if such is not present
> > then a function from std namespace?
> >
> > For motivating example "smart swap" that calls a member swap or
> > swap from namespace or std::swap. Since the checks are compile
> > time these will be likely removed by optimizing compiler
> > (like I comment out in following):
> >
> > template<typename T>
> > inline void smart_swap(T& a, T& b)
> > {
> > // if (T::swap(T& t) exists)
> > a.swap(b);
> > // else if (swap(T& a, T& b) is found) swap(a, b);
> > // else if (::swap(T& a, T& b) is found) ::swap(a, b);
> > // else std::swap(a, b);
> > }
> >
> > It is sure possible, but how to?
>
> I haven't been paying attention (sorry!) but isn't this what
> std::swap() is supposed to take care of?
Unfortunately no. The std::swap is actually required to be sort of
"usually fine enough" implementation for types that are
move-constructive AND move-assignable and has to be equivalent to
that:
template <class T>
void swap (T& a, T& b)
{
T c(std::move(a)); a=std::move(b); b=std::move(c);
}
> Or put differently, isn't the author of T responsible for the
> performance of std::swap(T&, T&) ?
Each developer (or group of such) may of course agree to take
whatever responsibilities. That does not affect with what library
from what other group they may be need to start integrating their
code next week.
In real code I have seen more often swap(T&, T&) implemented in
namespace of T; less often std::swap(T&, T&) specialized.
However I have seen also T::swap only.