Search code examples
c++templatesc++11numeric-limits

std::numeric_limits as a Condition


Is there a way that I can use std::numeric_limits<T>::is_integer and std::numeric_limits<T>::is_specialized to change template behavior?

For example can I do this:

template < typename T >
void foo( const T& bar )
{
    if( std::numeric_limits< T >::is_integer )
    {
        isInt( bar );
    }
    else if( std::numeric_limits< T >::is_specialized )
    {
        isFloat( bar );
    }
    else
    {
        isString( bar );
    }
}

Solution

  • The "obvious" answer is that you could use something like std::enable_if.

    For example:

    template<typename T>
    typename std::enable_if<std::numeric_limits<T>::is_integer, void>::type
        foo(const T &bar) { isInt(bar); }
    template<typename T>
    typename std::enable_if<std::numeric_limits<T>::is_specialized, void>::type
        foo(const T &bar) { isFloat(bar); }
    

    The problem with this approach is that this is ambiguous for (as an example) an int parameter, since numeric_limits<int>::is_specialized == true.

    To resolve this, I would simply use a better trait than numeric_limits, personally. You can also use boolean conditions to test for the exact condition you want:

    template<typename T>
    typename std::enable_if<std::numeric_limits<T>::is_specialized && !std::numeric_limits<T>::is_integer, void>::type
        foo(const T &bar) { isFloat(bar); }