在c ++ 11风格中输入类型转换的正确方法?

tty*_*ty6 3 c++ casting c++11

我有一个这样的课:

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;
}
Run Code Online (Sandbox Code Playgroud)

在(1)中,我收到了警告:

implicit conversion from int to size_type(aka unsigned long)
Run Code Online (Sandbox Code Playgroud)

我想知道摆脱那个警告的正确方法是什么?也许是这样的:

_data.resize(static_cast<decltype(_data)::size_type>(a)
Run Code Online (Sandbox Code Playgroud)

注意:我猜代码应该改为:

init(size_t a) 
Run Code Online (Sandbox Code Playgroud)

但是我们假设我们不能改变类接口.

Rev*_*lot 7

您的示例演员以正确的方式执行:

  1. 它明确地表明了施放的意图.
  2. 它会转换为正确的类型,并且可以防止将来的_data类型更改.
  3. 它使用正确的演员.

如果改变界面是不可能的,那就坚持下去吧.

在使用它之前,最好为输入添加健全性检查.在将其转换为unsigned之前检查负值是最基本和最有用的值.