鉴于
boost::histogram
的返回类型是高度模板化的,目前尚不清楚如何创建 boost::histogram::make_histogram()
对象作为类成员并使用 make_histogram()
在类构造函数中初始化它。
入门指南给出了使用包装器结构的示例,如下所示:
struct HolderOfStaticHistogram {
using axes_t = std::tuple<
boost::histogram::axis::regular<>,
boost::histogram::axis::integer<>
>;
using hist_t = boost::histogram::histogram<axes_t>;
hist_t hist_;
};
int main() {
using namespace boost::histogram;
HolderOfStaticHistogram hs;
hs.hist_ = make_histogram(axis::regular<>(5, 0, 1), axis::integer<>(0, 3));
}
但是,将
make_histogram
放入构造函数中不会编译,例如:
struct HolderOfStaticHistogram {
using axes_t = boost::histogram::axis::regular<>;
using hist_t = boost::histogram::histogram<axes_t>;
hist_t hist_;
HolderOfStaticHistogram() {
hist_ = boost::histogram::make_histogram(
boost::histogram::axis::regular<>(5, 0, 1));
}
};
int main() {
auto hist_container = HolderOfStaticHistogram();
}
/opt/compiler-explorer/libs/boost_1_80_0/boost/histogram/detail/axes.hpp:310:5: error: no member named 'resize' in 'boost::histogram::axis::regular<double, boost::use_default, boost::use_default, boost::use_default>'
t.resize(sizeof...(Us));
~ ^
/opt/compiler-explorer/libs/boost_1_80_0/boost/histogram/histogram.hpp:98:13: note: in instantiation of function template specialization 'boost::histogram::detail::axes_assign<boost::histogram::axis::regular<double, boost::use_default, boost::use_default, boost::use_default>, boost::histogram::axis::regular<double, boost::use_default, boost::use_default, boost::use_default> >' requested here
detail::axes_assign(axes_, std::move(unsafe_access::axes(rhs)));
^
<source>:53:15: note: in instantiation of function template specialization 'boost::histogram::histogram<boost::histogram::axis::regular<double, boost::use_default, boost::use_default, boost::use_default>, boost::histogram::unlimited_storage<std::allocator<char> > >::operator=<std::tuple<boost::histogram::axis::regular<double, boost::use_default, boost::use_default, boost::use_default> >, boost::histogram::unlimited_storage<std::allocator<char> > >' requested here
hist_ = boost::histogram::make_histogram(
一种解决方法是在调用
decltype
的表达式上使用 make_histogram
,如下所示:
#include <boost/histogram.hpp>
class HistContainer {
public:
using axis_t = boost::histogram::axis::regular<>;
using hist_t = decltype(boost::histogram::make_histogram(axis_t(10, 0, 10)));
hist_t hist;
HistContainer() {
hist = boost::histogram::make_histogram(axis_t(10, 0, 10));
}
};
int main() {
auto hist_container = HistContainer();
}
但是,这并不理想,因为我们必须构造
histogram
对象两次。拥有 boost::histogram
作为班级成员的正确方法是什么?
缺少一个元组:
using axes_t = std::tuple<boost::histogram::axis::regular<> >;
此外,使用基类/成员初始值设定项列表:
#include <boost/histogram.hpp>
namespace bh = boost::histogram;
struct HolderOfStaticHistogram {
using axes_t = std::tuple<bh::axis::regular<>>;
using hist_t = bh::histogram<axes_t>;
hist_t hist_;
HolderOfStaticHistogram() : hist_{bh::make_histogram(bh::axis::regular<>(5, 0, 1))} {}
};
int main() {
auto hist_container = HolderOfStaticHistogram();
}