簡體   English   中英

如何檢查模板的參數類型是否為整數?

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

在一些std模板函數的描述中,我看到了類似的東西:

如果模板參數是整數類型,則行為是這樣的。
否則,就是這樣等等。

我怎么做類似的測試? 也許dynamic_cast?

由於我寫的功能僅供我個人使用,我可以依靠自己只提供正確的參數,但為什么錯過學習的機會呢? :)

除了其他答案之外,應該注意的是,測試可以在運行時使用,也可以在編譯時使用,以根據類型是否為完整來選擇正確的實現:

運行時版本:

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

#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函數時,編譯器將“選擇”正確的實現,具體取決於模板參數是否為整數。

一種可能性

#include <type_traits> 
#include <iostream> 

struct trivial 
{ 
    int val; 
}; 

int main() 
{ 
    std::cout << "is_integral<trivial> == " << std::boolalpha 
        << std::is_integral<trivial>::value << std::endl; 
    std::cout << "is_integral<int> == " << std::boolalpha 
        << std::is_integral<int>::value << std::endl; 
    std::cout << "is_integral<float> == " << std::boolalpha 
        << std::is_integral<float>::value << std::endl; 

    return (0); 
} 

然后,您使用std::is_integral<>來確定操作。

如果無法使用C ++ 11點的特征, std::numeric_limits<T>::is_integer同樣的事情作為std::is_integral<T>::value ,並且可使用C ++ 98。

請注意,98版本是inte ger ,而不是interal

如果你的編譯器還不支持下一個標准的C ++特性, Boost.TypeTraits提供了is_integral <>(),如另一個響應中所述。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM