1

How should I write this to appease clang-tidy?

#include <vector>
int main()
{
    std::vector<int> v(10);
    size_t index = 2;
    auto it = v.begin() + index;
    auto rollover = (index + 1) % v.size();
}

clang-tidy complains

Clang-Tidy: Narrowing conversion from 'size_t' (aka 'unsigned long') to signed type '__gnu_cxx::__normal_iteratorstd::basic_string<char *, std::vectorstd::basic_string<char>>::difference_type' (aka 'long') is implementation-defined

If I use long for index, the mod operation narrows v.size() if I use the more sensible size_t for index the v.begin() + index narrows index. (Why is the iterators operator+ only defined for a signed type anyways? g++11.2.0)

Is there a way to get around this without using static_cast<long> all over the place?

C++ Insights demo

Captain Giraffe
  • 14,407
  • 6
  • 39
  • 67

0 Answers0