Distribution as a member of a class in C ++

I have two related questions regarding the use of distributions within classes.

  • Is there some basic distribution in C ++ to use a distribution as a member of a class without knowing what distribution it will be? I can not use templates (see Question 2)

    class Foo{ private: // could by any distribution std::base_distribution dist_; }; 
  • I have another Bar class that should have the Foo vector as a private member ( std::vector<Foo> ). The problem is that if Foo uses templates, then it is impossible to have a vector of different template arguments, which I want to get that way.

     class Bar { private: std::vector<Foo> foo_; }; 

boost::variant does not help, because I do not know the type of distributions. So this (for example) is not possible in my case:

 class Bar{ private: boost::variant<std::normal_distribution<>, std::uniform_real_distribution<> > dists_; }; 
+5
source share
2 answers

No, there are no base classes shared by all distribution patterns. Even if that were the case, your intended approach would not work due to fragmentation of objects .

However, it’s quite simple to create your own base class and extract from it.

 class base_distribution {}; template<typename ...Args> class normal_distribution : public base_distribution, public std::normal_distribution<Args...> {}; template<typename ...Args> class uniform_int_distribution : public base_distribution, public std::inform_int_distribution<Args...> {}; 

... etc. for any distributions you want to support. You will probably also need to delegate shell constructors to their actual distribution base class for maximum transparency.

At this point, slicing objects becomes a factor, so you cannot just drag base_distribution into a class as a member, or insert it into a vector, and expect it to work. You will have to use at least

 std::shared_ptr<base_distribution> 

as a member of a class or container value. At this point, to wrap this around, define any virtual methods that you need in your base_distribution class and implement them accordingly in the template subclasses.

+8
source

As far as I know, in C ++ there is no “base distribution class” or general distribution class. You have the concept of RandomNumberDistribution , but this is clearly not the same.

If you need a quick and dirty distribution class (and I mean dirty), I am currently using something like this ( .h , .cpp ).

As for your second question - you may need to inherit your template class inheritance from one non-standardized class, which you can place in your vector (you need to use pointer elements to avoid data overlay).

+1
source

Source: https://habr.com/ru/post/1264157/


All Articles