gpt4 book ai didi

c++ - 将 std::normal_distribution 绑定(bind)到 std::function 以存储在 std::vector 中

转载 作者:行者123 更新时间:2023-11-27 23:54:01 25 4
gpt4 key购买 nike

我正在尝试将几种不同类型的 c++ 发行版存储到一个容器中,我想我可以使用 std::function 来达到这个目的。我的尝试如下:

void print_rand(){
// Make the random number generator
std::random_device rd{};
std::mt19937 engine(rd());

// Store the distribution in a std::function
auto n1 = std::make_shared<std::normal_distribution<double>>(0,1);
std::function<double (std::mt19937)> fn = std::bind(&std::normal_distribution<double>::operator(), n1, std::placeholders::_1);

// Call the function to get a normally distributed number
std::cerr << fn(engine) << std::endl;
}

但我收到以下错误:

error: no matching function for call to ‘bind(<unresolved overloaded function type>, std::shared_ptr<std::normal_distribution<double> >&, const std::_Placeholder<1>&)’
std::function<double (std::mt19937)> fn = std::bind(&std::normal_distribution<double>::operator(), n1, std::placeholders::_1);

当我尝试专门化 operator() 调用的模板时:

std::function<double (std::mt19937)>  fn = std::bind(&std::normal_distribution<double>::operator()<std::mt19937>, n1, std::placeholders::_1);

我得到了同样的错误。

如有任何提示,我们将不胜感激!

最佳答案

以下是将 normal_distribution 放入 std::function 的方法:

std::normal_distribution<double> nd(0, 1);
std::function<double(std::mt19937&)> fn = nd;

没有 shared_ptr,没有 bind,没有 lambda,没有随机数引擎的复制(注意 &)。

关于c++ - 将 std::normal_distribution 绑定(bind)到 std::function 以存储在 std::vector 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44011547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com