Saturday, June 16, 2007

Consider support for a non throwing swap

so u can use the default implementation of swap. or you can provide a total specialization of a template to provide a more efficient version of swap.

 

the general idea is that the class provides a public swap function and then we provide a total specialization of the swap template of std namespace.

 

this is the trend in stl too, all containers ( vector, list etc) provide a public swap function and a total specialization of the general swap template.

 

c++ allows partial specialization of class templates but not partial specialization of function templates

template< class t>

swap <widget<t>> ( widget <t> & a , widget<t>&b) {..call fn defined in class).}

 

this doesnt compile

the way to get around this is you define the swap you want as before but in the namespace of your class ( assuming class is not in std namespace) then after that c++ name lookup rules will take care of picking the right implementation for you ( koenig rule ,argument dependent lookup)

 pimpl idiom is that you keep a pointer to implementation inside the object

make sure that your public member swap function shudnt throw an exception. i dont understand why ????

what is strong exception safety guarantee ???

 

from a client perspective if you are calling swap, then use a using declaration for general swap and make the actual call as swap (...) and not std::swap(...)

things to remember:

provide a swap member function, when std::swap would be inefficient for your type make sure your swap doesn't throw exceptions

if you offer a member swap also offer a non member swap that calls the member for classes ( not templates) specialize std::Swap too

when calling swap employ a using declaration for std::Swap then call without namespace qualification

its fine to totally specialize std templates for user defined types , but never try to add something completely new to std

No comments: