簡體   English   中英

添加產生的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));
}

正如這里所解釋的那樣在算術運算中使用short時,必須首先將其轉換為int 。因此,編譯器實際上正在嘗試找到正確的MyFunc(int,int)並且必須在MyFunc(short,short)MyFunc(float,float) MyFunc(short,short)之間進行選擇。 MyFunc(float,float) ,因此模棱兩可。

在添加期間,如果操作數小於int ,則它們被提升為int ,而i + 1的結果也是int 有關更多信息,請查看此 此時,在過載分辨率期間,會發生浮點類型轉換的積分。

暫無
暫無

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

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