2015-10-05 82 views
1

我想有以下如何包括C++不在參數

template <typename T_unsigned, typename T_signed> bool foo(T_unsigned input) 
{ 
    T_signed temp= ((T_signed) input)-100;  
    //use temp for calculations to figure out myBool 
    return myBool; 
} 

中的代碼一樣T_signed的模板類型的模板類型雖然上面是實際的代碼我寫,大大的簡化相信這是阻止編譯代碼的原因。我如何讓編譯器根據類型輸入是隱式地計算出T_signed的類型?任何幫助讚賞。

+8

您正在尋找['std :: make_signed'](http://en.cppreference.com/w/cpp/types/make_signed)。 –

回答

2

東西like this,使用std::make_signed

#include <iostream> 
#include <type_traits> 

template <typename Tu> 
bool foo(Tu input) { 
    std::cout << std::is_signed<Tu>::value << std::endl; 

    typedef typename std::make_signed<Tu>::type Ts; 
    Ts temp = input - 100; 

    return (temp < 0); 
} 

int main() { 
    std::cout << foo(32u) << std::endl; 
} 

您還可以添加std::enable_ifstatic_assert以確保類型,傳遞的真的是無符號。