mercredi 25 septembre 2019

Polymorphism with Distribution in C++11

I have a problem where I want a single object to represent any distribution class (polymorphism) used in random library in c++11. Since distribution does not have a common base class as far as I know I am using factory pattern to solve my problem. Is there a better way to do so ? I am adding the code below which has some errors

#include <iostream>
#include<random>

using namespace std;

class Distribution 
{
public:
    void *distribution;
    virtual void get_distribution() = 0;
};

class normal_dist: public Distribution
{
public:
    //normal_distribution<double> *distribution;
    void get_distribution()
    {
        distribution = new normal_distribution<double>(5.0,2.0); 
    }
};

class uniform_real_dist: public Distribution
{
public:
    //uniform_real_distribution<double> *distribution;
    void get_distribution()
    {
        distribution = new uniform_real_distribution<double>(0.0,1.0);
    }
};

class Helper
{
public:
    Distribution *dist;
    default_random_engine generator;

Helper(string dist_type) 
{
    if(dist_type == "normal")
    {
        dist = new normal_dist;
        dist->get_distribution();
    }
}
};


int main() {

Helper *help = new Helper("normal");
cout<<(*(help->dist->distribution))(help->generator);


// your code goes here
return 0;
}

My questions are three fold 1) Is there a base class of distribution 2) if no, is there a way to create polymorphism 3) Whether the above code is correct approach and what is the bug and how to solve this. I would be very thankful if someone could help me on this

Aucun commentaire:

Enregistrer un commentaire