tty6
tty6

Reputation: 1233

Correct way to type casting in c++11 style?

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

Answers (3)

Paul Evans
Paul Evans

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

Revolver_Ocelot
Revolver_Ocelot

Reputation: 8785

Your example cast does it the right way:

  1. It explicitely states intent to cast.
  2. It casts to the correct type and is protected from future _data type changes.
  3. It uses the right cast.

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

ForceBru
ForceBru

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

Related Questions