2017-05-31 3 views
1

私は、テンプレートが1つのベクトルの値を検索し、計算されたインデックスを使用して特定の位置に値を取得するコードベースを持っています。キャストなしのインデックスとポインタの算術を混在させるときのC4365の回避

#pragma once 
#pragma warning(disable: 4514) 
#pragma warning(disable: 4710) 
#pragma warning(disable: 4189) 
#include <vector> 

int main(int, char *[]) 
{ 
    //contrived example, never mind the non C4365 issues in this code 
    //I am aware that this makes not a lot of sense runtime wise 
    //This question is about a compiler warning 
    int target; 
    std::vector<char> first; 
    std::vector<long> second; 

    auto it = std::find(first.begin(), first.end(), target); 
    //Warning C4365 '...': conversion from '...' to '...', signed/unsigned mismatch 
    std::size_t pos = it - first.begin(); //from int to std::size_t 
    long result = second.at(pos); 

    return 0; 
} 

私はC4365警告で特に興味を持っています:ここで

は、Visual Studioのために作られたソースのビットが荒いアイデアを与えることです。 MSDNにはエントリがあり、これに関連する別の stackoverflow質問があります。

私はこのstd::size_t pos = static_cast<size_t>(it - first.begin());が警告を削除することを理解します。

私の質問は、警告を避けるためにキャストを必要としないように上記の検索と値を書き込むことができるかどうかです。

EDIT:この警告は警告レベル4であり、デフォルトではオフであるとは言及していませんでした。

+1

'auto pos = it - first.begin();'? – NathanOliver

+0

@ NathanOliverこの例では、型はintになり、警告がunsignedが必要な次の行に移動します。 – Johannes

+0

それはありますか?それは私のマシンではありません。 – NathanOliver

答えて

1

intを有効にするイテレータに追加するので、以下のコードは警告を生成しません。

int main(int, char *[]) 
{ 
    //contrived example, never mind the non C4365 issues in this code 
    //I am aware that this makes not a lot of sense runtime wise 
    //This question is about a compiler warning 
    int target; 
    std::vector<char> first; 
    std::vector<long> second; 

    auto it = std::find(first.begin(), first.end(), target); 
    auto it2 = second.begin() + (it - first.begin()); 
    long result = *it2; 

    return 0; 
} 
関連する問題