将 std::normal_distribution 绑定到 std::function 以存储在 std::vector 中
binding std::normal_distribution to a std::function for storage in std::vector
我正在尝试将几种不同类型的 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::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,没有随机数引擎的复制(注意 &
)。