How to check that template's parameter type is integral?

前端 未结 4 630
南笙
南笙 2021-01-12 09:11

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.

4条回答
  •  一生所求
    2021-01-12 09:47

    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  (if using Boost) 
    // or  (if using c++1x)
    // In the following, is_integral shoudl be prefixed by either boost:: or std::
    
    template 
    void algorithm(const T & t)
    {
        // some code
    
        if (is_integral::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 
    #include 
    
    template 
    typename boost::enable_if >::type
    algorithm(const T & t)
    {
        // implementation for integral types
    }
    
    template 
    typename boost::disable_if >::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.

提交回复
热议问题