davka - 9 months ago 53

C++ Question

In the description of some std template function I saw something like:

if the template parameter is of integral type, the behavior is such and such.

otherwise, it is such and such.

How can I do a similar test? Perhaps dynamic_cast?

Since the function I write is for my personal use I can rely on myself to supply only correct parameters, but why miss a chance to learn something? :)

Answer Source

In addition to the other answers, it should be noted that the test can be used at runtime but also at compile-time to select the correct implementation depending on wether the type is integral or not:

Runtime version:

```
// Include either <boost/type_traits/is_integral.hpp> (if using Boost)
// or <type_traits> (if using c++1x)
// In the following, is_integral shoudl be prefixed by either boost:: or std::
template <typename T>
void algorithm(const T & t)
{
// some code
if (is_integral<T>::value)
{
// operations to perform if T is an integral type
}
else
{
// operations to perform if T is not an integral type
}
// some other code
}
```

However, this solution can be improved when the implementation of the algorithm greatly depends on the test. In this case, we would have the test at the top of the function, then a big `then`

block and a big `else`

block. A common approach in this case is to overload the function and make the compiler select the correct implementation using SFINAE. An easy way to do this is to use `boost::enable_if`

:

```
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_integral.hpp>
template <typename T>
typename boost::enable_if<boost::is_integral<T> >::type
algorithm(const T & t)
{
// implementation for integral types
}
template <typename T>
typename boost::disable_if<boost::is_integral<T> >::type
algorithm(const T & t)
{
// implementation for non integral types
}
```

When invoking the `algorithm`

function, the compiler will "select" the correct implementation depending on wether the template parameter is integral or not.