![](/img/trans.png)
[英]Getting results from functions with 'void' return type, while resulting variable is one of the input arguments - C++
[英]What is the C++ type resulting from addition
我收到了“模糊調用”編譯錯誤:
short i;
MyFunc(i+1, i+1);
MyFunc有兩個定義 - 一個帶兩個短褲,另一個帶兩個浮子。
我寫的時候:
MyFunc(i, i+1);
沒有錯誤 - 編譯器推斷短。
我的問題是,為什么“短”+ 1可能會導致浮點,我怎樣才能避免遍歷所有代碼並添加顯式的強制轉換,例如:
MyFunc((short)(i+1), (short)(i+1));
謝謝。
i+1
被提升為int
因為short
是比int
更小的整數類型。
所以MyFunc(i+1, i+1);
是“ MyFunc(int, int);
”
您可以通過添加執行預期調度的重載來解決模糊性,例如:
void MyFunc(short, short);
void MyFunc(float, float);
template <typename T1, typename T2>
std::enable_if<std::is_floating_point<T1>::value ||
std::is_floating_point<T2>::value>
MyFunc(T1 t1, T2 t2)
{
MyFunc(static_cast<float>(t1), static_cast<float>(t2));
}
template <typename T1, typename T2>
std::enable_if<!std::is_floating_point<T1>::value &&
!std::is_floating_point<T2>::value>
MyFunc(T1 t1, T2 t2)
{
MyFunc(static_cast<short>(t1), static_cast<short>(t2));
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.