如何检查模板的参数类型是否为整数? [英] How to check that template's parameter type is integral?

查看:43
本文介绍了如何检查模板的参数类型是否为整数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一些标准模板函数的描述中,我看到了类似的东西:

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

如果template参数为整数类型,则其行为为so.诸如此类.
否则,就是这样.

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

如何进行类似的测试?也许是dynamic_cast?

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? :)

推荐答案

除了其他答案外,还应注意,该测试可以在运行时使用,也可以在编译时使用,以根据情况选择正确的实现该类型是否为整数:

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:

运行时版本:

// 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
}

但是,当算法的实现很大程度上取决于测试时,可以改进此解决方案.在这种情况下,我们将在函数顶部进行测试,然后是一个大的 then 块和一个大的 else 块.在这种情况下,一种常见的方法是重载函数,并使编译器使用SFINAE选择正确的实现.一种简单的方法是使用 boost ::enable_if :

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
}

调用 algorithm 函数时,编译器将根据模板参数是否为整数来选择"正确的实现.

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

这篇关于如何检查模板的参数类型是否为整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆