在C++中作为类的成员分发

beg*_*neR 5 c++ boost class distribution c++11

关于在类中使用分布,我有两个相关的问题.

  1. 在C++中是否存在某种基本分布,以便将分布用作类成员而不知道它将是哪个分布?我不能使用模板(见问题2)

    class Foo{
        private:
            // could by any distribution
            std::base_distribution dist_;
    
    };
    
    Run Code Online (Sandbox Code Playgroud)
  2. 我有另一个类Bar应该有Foo一个私有成员的向量(std::vector<Foo>).问题是如果Foo使用模板,那么就不可能有一个不同模板参数的向量,这正是我想要的.

    class Bar {
        private:
            std::vector<Foo> foo_;
    
    };
    
    Run Code Online (Sandbox Code Playgroud)

boost::variant也没有帮助,因为我不知道分布的类型.所以这(例如)在我的情况下是不可能的:

class Bar{
    private:
        boost::variant<std::normal_distribution<>, std::uniform_real_distribution<> > dists_;
};
Run Code Online (Sandbox Code Playgroud)

Sam*_*hik 8

不,所有分发模板都没有共享基类.即使存在,由于对象切片,您的预期方法无论如何都不会起作用.

但是,创建自己的基类并从中派生它应该相当容易.

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...> {};
Run Code Online (Sandbox Code Playgroud)

...等等,对于您想要支持的任何发行版.您可能还需要将包装器的构造函数委托给它们的实际分发基类,以获得最大的透明度.

此时,对象切片成为一个因素,因此您不能只base_distribution将其作为成员推送到类中,或者将其推送到向量中,并期望它能够正常工作.你必须使用,至少是一个

std::shared_ptr<base_distribution>
Run Code Online (Sandbox Code Playgroud)

作为类成员或容器值.此时,为了将其包装起来,定义base_distribution类中需要的任何虚拟方法,并在模板子类中适当地实现它们.