Home > OS >  how to derive a class (from e.g. Eigen::VectorXf) with (only) an extra static method while retaining
how to derive a class (from e.g. Eigen::VectorXf) with (only) an extra static method while retaining

Time:09-14

Let's say I need to attach some 'type id' to my Eigen::VectorXf vectors.

So far I have something like this (simplified for brevity):

struct MyVector123 
{
    Eigen::VectorXf vec;
    static int id() {return 123};
};

struct MyVector456
{
    Eigen::VectorXf vec;
    static int id() {return 456};
};

(Please don't argue with me it's a poor design and I should not do this. You might be very right, but the legacy code I'm using requires me to do so...)

This is working fine but forces me to use .vec everywhere. I was wondering if I could do slightly better by deriving from Eigen::VectorXf directly, something like:

struct MyVector123 : public Eigen::VectorXf
{
    static int id() {return 123};
};

struct MyVector456 : public Eigen::VectorXf
{
    static int id() {return 456};
};

The problem is that this doesn't seem to allow me to recycle all the base constructors, e.g. MyVector123 x = MyVector123::Random(10) generates a compile error:

No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called

Am I missing something simple to make this work?

CodePudding user response:

You need to inherit the constructor (c 11)

struct MyVector123 : public Eigen::VectorXf
{
    using Eigen::VectorXf::VectorXf;
    static int id() {return 123};
};
  • Related