Reputation: 16321
Given the following:
Here is the code itself for convenience (and I am not sure my link is working):
#include <iostream>
#include <vector>
#include <stdint.h>
using namespace std;
int main()
{
cout<<"Hello World";
std::vector<std::string> test_vect {"1", "2"};
long unsigned int size = static_cast<long unsigned int>(test_vect.size());
std::cout << "size: " << size << std::endl;
return 0;
}
And the following compile options: g++ file.c -Wall -Wextra "-Werror" "-Wuseless-cast"
You can see here that I am casting vector.size()
to long unsigned int
, this gets flagged up as a useless cast on Wandbox (my link) however the same code running on my linux box does not give a warning - but it will give me a different warning if I dont cast it.
I understand that the two unsigned long
vs size_t
can be different. But what I am trying to do is write some code that has no warnings with all the casting warnings set (maybe this is optamisitic when cross compiling).
So, one compiler complains that I am converting types, so I cast, but then another compiler is complaining about useless cast - so I remove the cast - and around we go :(
Is there a good approach to this so that I dont get warnings on either compilers?
I was going to just remove the -Wuseless-cast
option, but I thought I would see if anyone has other ideas...
Upvotes: 4
Views: 241
Reputation: 2117
As Lightness Races in Orbit pointed out, size_t
is an option, it should have an appropriate macro to make compilers happy, if you somehow don't want to use that - making your variable auto
or decltype(test_vect.size())
would be another option:
auto size = test_vect.size();
or
decltype(test_vect.size()) size = test_vect.size();
Upvotes: 2
Reputation: 385088
what I am trying to do is write some code that has no warnings with all the casting warnings set (maybe this is optamisitic when cross compiling)
It's optimistic when cross compiling if you have casts.
Is there a good approach to this so that I dont get warnings on either compilers?
Don't have casts. Make your variable be of type std::size_t
.
I was going to just remove the
-Wuseless-cast
option
That's the other option.
Upvotes: 5
Reputation: 1535
One argument that comes to mind is: Why does your size variable need to be long unsigned
at all instead of std::size_t
?
Just in case there is a compelling reason for that, how about (C++17):
long unsigned size;
if constexpr(sizeof(long unsigned)!=sizeof(std::size_t))
size = static_cast<long unsigned>(...);
else
size = ...;
Upvotes: 1