我有一个问题,我希望一个对象代表c ++ 11中随机库中使用的任何分布类(多态性)。据我所知,由于发行版没有通用的基类,因此我正在使用工厂模式来解决我的问题。有更好的方法吗?我正在添加下面的代码,其中有一些错误
#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;
}
我的问题是三折
1)是否有基本的分配类别
2)如果否,是否有创建多态的方法
3)以上代码是否正确,错误是什么以及如何解决。如果有人可以帮助我,我将非常感谢
如果您知道哪种分布适用于哪种情况,那么使用模板是更好的方法。这是相同的示例代码:
template<class C, template <class> class M>
M<C> getDistributionObject(const C& arg1, const C& arg2)
{
return M<C>(arg1,arg2);
}
int main() {
auto normalDistribution = getDistributionObject<double,normal_distribution>(5.0,2.0);
return 0;
}