I need a common rule for warnings in x64 mode. Which way is better?
Consider the following lines of some code
const int N = std::max_element(cont.begin(), cont.end()) - cont.begin();
or
const int ARR_SIZE = 1024;
char arr[ARR_SIZE];
//...
const int N = std::max_element(arr, arr + ARR_SIZE) - arr;
It is my usual code. I have no problems with x86.
But if I run compiler in x64 mode I have some warnings:
conversion from 'std::_Array_iterator<_Ty,_Size>::difference_type' to 'int', possible loss of data
conversion from '__int64' to 'int', possible loss of data
I want to solve these problems by common rule. Which way is better?
Making
static_cast
:const int N = static_cast<int>( std::max_element(cont.begin(), cont.end()) - cont.begin() );
I think this is not general-purpose. And too much letters.
Replace output type with
ptrdiff_t
:const ptrdiff_t N = std::max_element(cont.begin(), cont.end()) - cont.begin();
What should I do then with this unknown type ptrdiff_t? I'll get another dozen warnings then. I want to make many operations with N: save, addition, multiplication, cycles and etc. Important: but what if
std::_Array_iterator<_Ty,_Size>::difference_type
andptrdiff_t
are different types?Replace output type with
std::_Array_iterator<_Ty,_Size>::difference_type
://h-file struct S { type mymember; // What is the type? }; //cpp-file typedef std::vector<int> cont_t; const cont_t::difference_type N = std::max_element(cont.begin(), cont.end()) - cont.begin(); // Save N S mystruct; mystruct.mymember = N; // What type of mystruct.mymember?
How should I save N? What type of mystruct.mymember? I don't know it in h-file.
Your solution.