jeudi 6 décembre 2018

How to validate input parameters in C++ constructor?

Following example shows the crux of the problem. I need to initialize const members of a class. This can only be done in the initializer-list and not in constructor body. I want to assert or throw an error if input to the constructor is invalid.

class A {
 // In following constructor, how do we make sure if params.size()
 // is at least 3.
 A(const std::vector<int>& params):
  x(params[0]), y(params[1]), z(params[3]) {}
private:
  const int x;
  const int y;
  const int z;
};

Please advise how to achieve this in Modern C++ (11 and later)

Aucun commentaire:

Enregistrer un commentaire