Reputation: 1233
I have a class like this:
class A {
void init(int a){
_data.resize(a); //! (1)
}
//other parts of the code are not important ...
private:
std::list<std::vector<double>> _data;
}
In (1) i got warning with text:
implicit conversion from int to size_type(aka unsigned long)
I want to know what is the correct way to get rid of that warning? Maybe something like that:
_data.resize(static_cast<decltype(_data)::size_type>(a)
Note: I guess that the code should be changed to:
init(size_t a)
But let's assume that we can not change the class interface.
Upvotes: 3
Views: 1748
Reputation: 27567
The most correct way is as you say:
_data.resize(static_cast<decltype(_data)::size_type>(a));
But the big problem is signed vs unsigned
and you say you're stuck with int
so you use:
_data.resize(static_cast<unsigned int>(a));
Upvotes: 4
Reputation: 8785
Your example cast does it the right way:
_data
type changes.So stick with it, if changing interface is out of question.
It would be good to add sanity checks for input before you will use it. Checking for negative value before you cast it to unsigned is most basic and useful one.
Upvotes: 7
Reputation: 44828
As simple as this:
_data.resize(std::size_t(a));
As crazy as this:
_data.resize(static_cast<std::size_t>(a));
C-style casts also supported:
_data.resize((std::size_t)a);
Upvotes: 2