Using type traits to overload functions and objects

One issue that C++ had to deal with when C++11 was created was how to handle resizing std::vector, which is capable of taking any type, including types that can throw from std::move(). When resizing, new memory is created and the elements from the old vector are moved to the new vector. This works great because, if std::move() cannot throw, the resize can safely be performed as once the resizing function starts to move elements from one array to the other, no errors can occur.

If std::move() can throw, however, it is possible that part of the way through the loop, an error could occur. The resize() function, however, would have no way to put the old memory back to normal as attempting to move to the old memory could also throw an exception. In this case, resize() performs a copy instead of a move. A copy ensures that the old memory has a valid copy of each object; so, if an exception is thrown, the original array is left intact and the exception can be thrown as needed.

In this recipe, we will explore how this is done by changing the behavior of a template class using traits.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset