vendredi 17 avril 2020

What is the best way to handle a conditional number of member variables?

I am trying to write a C++ library to plot either 2D or 3D data. My idea is to have a Plot class that contains all the information regarding the axes, title, legend, and so on. So Plot would have a member Axes, a member Title, etc.

class Plot { public: plot() {...} private: Axes axes; Legend legend; ... }

I want the API to be as intuitive as possible, so that it could be used (easy example) as follows:

int main() {
    std::vector<float> x_data { 1.0, 2.0, 3.0, 4.0, 5.0 };
    std::vector<float> y_data { 5.0, 3.0, 3.0, 3.0, 5.0 };
    std::vector<float> z_data { 8.0, 7.0, 1.0, 2.0, 3.0 };

    Plot plt;    // initializes a generic instance of a plot

    // The user can decide to plot 2D data
    plt.plot2D(x_data, y_data);            // only takes 2 input parameters

    // Or to plot 3D data
    plt.plot3D(x_data, y_data, z_data);    // takes 3 input parameters
}

The problem is (for example) Plot's Axes member.

In the 2D case I would like Axes to be something like:

class Axes
{
public:
    Axes() {...}
    std::string getAxesInformation()
{
    // does something with axes x and y
}

private:
    Axis x;
    Axis y;
}

While in the 3D case I would like it to be something like this:

class Axes
{
public:
    Axes() {...}
    std::string getAxesInformation()
{
    // does something with axes x, y AND z
}

private:
    Axis x;
    Axis y;
    Axis z;
}

How should I handle a different number of member variables? One option of course to save a bool to keep track of the existence of z and stuff, but that doesn't seem ideal.

I would like z not to be instantiated at all.

Aucun commentaire:

Enregistrer un commentaire