Selecting an optimal operator for a template parameter
Imagine that we are working with classes from different vendors that implement different numbers of arithmetic operations and have constructors from integers. We do want to make a function that increments by any one class that is passed to it. Also, we want this function to be effective! Take a look at the following code:
template <class T> void inc(T& value) { // TODO: // call ++value // or call value ++ // or value += T(1); // or value = value + T(1); }
Getting ready
Some basic knowledge of the C++ templates, and the Boost.TypeTrait
or standard library type traits is required.
How to do it...
All the selecting can be done at compile time. This can be achieved using the Boost.TypeTraits
library, as shown in the following steps:
- Let's start by making correct functional objects:
namespace detail { struct pre_inc_functor { template <class T> void operator()(T& value) const { ...