动态分配许多 Boost::直方图对象



我需要动态创建(并在以后删除(许多 Boost::直方图对象,每个对象都有不同数量的轴和 bin 边界,但我认为我不能创建一个具有make_histogram工厂函数的对象。 它不返回指针,所以我无法删除该对象。 任何人都可以提供示例代码来动态分配单个直方图吗?

我知道,查看代码并查看所有这些模板和auto返回类型可能会令人生畏。

你可以做的是让自己成为几个方便的工厂,以获得一个独特的(或共享的(指针:

#include <boost/histogram.hpp>
#include <memory>
#include <tuple>
template <class Storage, class Axis, class... Axes,
class = boost::histogram::detail::requires_axis<Axis>>
auto make_unique_histogram_with(Storage&& storage, Axis&& axis,
Axes&&... axes) {
auto a =
std::make_tuple(std::forward<Axis>(axis), std::forward<Axes>(axes)...);
using U = boost::histogram::detail::remove_cvref_t<Storage>;
using S = boost::mp11::mp_if<boost::histogram::detail::is_storage<U>, U,
boost::histogram::storage_adaptor<U>>;
return std::make_unique<boost::histogram::histogram<decltype(a), S>>(
std::move(a), S(std::forward<Storage>(storage)));
}
template <class Axis, class... Axes,
class = boost::histogram::detail::requires_axis<Axis>>
auto make_unique_histogram(Axis&& axis, Axes&&... axes) {
return make_unique_histogram_with(boost::histogram::default_storage(),
std::forward<Axis>(axis),
std::forward<Axes>(axes)...);
}
int main() {
auto histogram = make_unique_histogram(
boost::histogram::axis::regular<>(6, -1.0, 2.0, "x"));
(*histogram)(0.1, boost::histogram::weight(1.0));
}

代码取自boost/直方图/make_histogram.hpp,并略有修改。以类似的方式,您可以重写其余的帮助程序。

提醒:您将需要一个兼容 C++14 的编译器。

最新更新