Optimizing algorithms using traits
Instead of talking about this topic in a generic abstract way, we will use a classic optimized copy example to show the usage of type traits. Consider the standard library algorithm known as copy
, shown here:
template<typename It1, typename It2>It2 copy(It1 first, It1 last, It2 out);
Obviously, we can write a generic version of copy()
for any iterator types—that is, It1
and It2
here. However, as explained by the authors of the Boost library, there are some circumstances where the copy operation can be performed by memcpy()
. We can use memcpy()
if all of the following conditions are satisfied:
- Both types of iterators,
It1
andIt2
, are pointers It1
andIt2
must point to the same type, except for const and volatile qualifiers- A trivial assignment operator must be provided by the type that
It1
points to
Here, the trivial assignment operator means that the type is either a scalar type or that one of the following...