I'm having a rather strange warning being reported by clang-tidy 12.0.1. In the following code:
#include <vector>
int main()
{
std::vector<int> v1;
const auto a = v1.begin() v1.size();
return 0;
}
I see this warning being triggered:
error: narrowing conversion from 'std::vector<int>::size_type' (aka 'unsigned long long') to signed type 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<int>>>::difference_type' (aka 'long long') is implementation-defined [bugprone-narrowing-conversions,cppcoreguidelines-narrowing-conversions,-warnings-as-errors]
const auto a = v1.begin() v1.size();
^
It was my understanding that when operating two integers with the same size but different signedness, the signed integer is converted to unsigned, not the other way around. Am I missing something here?
CodePudding user response:
To show the actual types involved :
// Operator accepts difference type
// https://en.cppreference.com/w/cpp/iterator/move_iterator/operator_arith
// constexpr move_iterator operator ( difference_type n ) const;
#include <type_traits>
#include <vector>
#include <iterator>
int main()
{
std::vector<int> v1;
auto a = v1.begin();
auto d = v1.size();
// the difference type for the iterator is a "long long"
static_assert(std::is_same_v<long long, decltype(a)::difference_type>);
// the type for size is not the same as the difference type
static_assert(!std::is_same_v<decltype(d), decltype(a)::difference_type>);
// it is std::size_t
static_assert(std::is_same_v<decltype(d), std::size_t>);
return 0;
}
CodePudding user response:
Since C 20 a simple fix is to use std::sszie
:
const auto a = v1.begin() std::ssize(v1);