Search code examples
c++typesmacrosprecompile

How do I use typedef with class initializer parameters in C++?


I'm asking this question like this because I don't know how to phrase it better.

Right now, I'm writing a 3D-Application using the Eigen library. Eigen only has a Vector class, but I need distinct vector and point data types.

Both can be represented by an

Eigen::Vector4d(x,y,z,w) 

where w is 1 for a point and 0 for a vector.

I know that I can define a type by using

typedef vec3d Eigen::Vector4d

or

#define point3d Eigen::Vector4d

but is there a way to define it in a way so that w is always going to be 0 for a vector and 1 for a point?

typedef vec3d(x,y,z) Eigen::Vector4d(x,y,z,w) 

doesn't work.


Solution

  • You can inherit from it and provide a new constructor:

    struct vec3d : Eigen::Vector4d {
        vec3d(double x, double y, double z) : Vector4d(x, y, z, 0) {}
    };
    

    Or, what I would prefer, is to write a factory function like:

    Eigen::Vector4D make_vector(double x, double y, double z) {
        return {x, y, z, 0};
    }