Search code examples
c++constructordelegating-constructor

C++ Error checking before constructor delegation


I have a constructor that creates a matrix from size_t dimensions, I want to add support for int dimensions. However, before passing the ints to the size_t constructor I would like to make sure that they are positive.

 Matrix(vector<double> vals, int rows, int cols ) 
 \\throw something if rows<= 0 || cols<= 0
:Matrix(vals,static_cast<size_t>(rows), static_cast<size_t>(cols))

Is something like this possible?


Solution

  • Pass them through a function,

    int enforce_positive(int x) 
    { 
        if (x <= 0) { 
            throw something; 
        } 
        return x; 
    }
    
    Matrix(vector<double> vals, int rows, int cols ) 
      : Matrix(vals,
               static_cast<size_t>(enforce_positive(rows)), 
               static_cast<size_t>(enforce_positive(cols)))
    

    You can make this a template, of course.

    You could also use a "proof type" and make the condition explicit in the prototype. Something like

    temolate<typename T>
    class Positive
    {
    public:
        explicit Positive(T x): val(x)
        {
            if (val <= 0) {
                throw something;
            }
        }
        operator T() const { return val; }
    private:
        T val;
    };
    
    Matrix(const vector<double>& vals,
           Positive<int> rows,
           Positive<int> cols ) 
      : Matrix(vals,
               static_cast<size_t>(rows), 
               static_cast<size_t>(cols))
    
    //...
    int x = ...;
    int y = ...;
    Matrix m(stuff, Positive(x), Positive(y));