downcasting question

operator*= in DenseMatrix, can be completely removed, but in that case returned value will be a DenseVector& and manual downcasting to DenseMatrix& is needed.
Is there a more clear approach from mine?

1
2
3
4
5
6
7
8
9
struct DenseVector
{
	DenseVector &operator*=(double s) { /* do things */ return *this; }
};

struct DenseMatrix : public DenseVector
{
	DenseMatrix &operator*=(double s) { return static_cast<DenseMatrix&>(static_cast<DenseVector&>(*this) *= s); }
};
struct DenseMatrix : public DenseVector

Every matrix is a vector? This doesn't sound like a workable design.

As for operator*=, if it is part of interface that the matrix implements, why not just make it virtual?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <valarray>

struct DenseVector {
    std::valarray<double> data;
    DenseVector(size_t sz) : data(sz) {}
    virtual DenseVector& operator*=(double n)
    {
        data *= n;
        return *this;
    }
};

struct DenseMatrix : public DenseVector {
    DenseMatrix(size_t r, size_t c) : DenseVector(r*c) {}
};

int main()
{
        DenseMatrix m(2, 2);
        m *= 10;
}
Last edited on
Your approach does not fix the problem:
DenseMatrix &m2 = m *= 10;
returns error.
Okay, to get that to compile, you do need something similar to what you wrote., for example (given non-virtual base class operator*=)
1
2
3
4
5
    DenseMatrix& operator*=(double n)
    {
        DenseVector& dv = *this;
        return static_cast<DenseMatrix&>(dv *= n);
    }


Or you could redesign the class hierarchy so that it makes more sense -- look at how existing matrix libraries are structured, for example.
Last edited on
Topic archived. No new replies allowed.