簡體   English   中英

C ++為輸入類型選擇模板輸出類型

[英]C++ Choose template output type for input type

考慮我要實現以下功能:

template<typename InputType, typename = typename std::enable_if<std::is_arithmetic<InputType>::value>::type>
inline InputType degreeToRadians(InputType degree)
{
    return degree * (PI / 180.0);
}

如何找到給定InputType的正確OutputType? 由於InputType可能是某個整數,因此該函數將返回錯誤的結果,因為計算出的數字將轉換為整數InputType。 我還考慮過只返回一個長整數(我認為是最大的浮點數),但這似乎浪費了內存。 您會提出什么解決方案? 順便說一句,我不想​​在每次調用此函數時都包含模板規范:

float someFloat = degreeToRadians<float>(someIntegral);

在C ++ 11中:

template<typename InputType,
         typename = typename std::enable_if<std::is_arithmetic<InputType>::value>::type>
auto degreeToRadians(InputType degree)
-> decltype(degree * (PI / 180.0))
{
    return degree * (PI / 180.0);
}

在C ++ 14中:

template<typename InputType,
         typename = std::enable_if_t<std::is_arithmetic<InputType>::value>>
auto degreeToRadians(InputType degree)
{
    return degree * (PI / 180.0);
}

順便說一句,您可能想使用InputType ,我的意思是PI180改為具有InputType類型。

暫無
暫無

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

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