boostorg / histogram

Fast multi-dimensional generalized histogram with convenient interface for C++14
Boost Software License 1.0
315 stars 73 forks source link

how to specify the full type for boost::histogram::histogram (instead of "auto") #260

Closed jvo203 closed 4 years ago

jvo203 commented 4 years ago

This is not a bug but a newbie question. All the boost.histogram examples and the source code make a heavy use of "auto". But unfortunately one cannot declare "auto h" in an own class header.

I need to separate the declaration and its corresponding allocation of boost.histogram via make_histogram():

SeedHist2D.hpp: class XXX { boost::histogram::histogram _hist; //putting "auto _hist;" does not work in here, the compiler complains }

then in SeedHist2D.cpp: _hist = make_histogram(axis::regular(600, x_min, x_max, "_x"), axis::regular(600, y_min, y_max, "_y"));

Combing through the source code of boost.histogram does not help much, it is full of templates and autos!!! Is there a way to learn the real type hiding behind auto?

HDembinski commented 4 years ago

Hm, I answered this in another issue, but now I cannot find it. This should be documented in the user guide, so please keep this issue open. I recommend to use decltype.

namespace bh = boost::histogram;

// in .hpp
class XXX {
  using histogram_t = decltype(bh::make_histogram(bh::axis::regular<>(), bh::axis::regular<>()));
  histogram_t hist_;
};

// in .cpp
XXX x;
x.hist_ = bh::make_histogram(<etc etc>);
HDembinski commented 4 years ago

If your class needs to store histograms with a variable number of axes, you should do:

// in .hpp
namespace bh = boost::histogram;

// in .hpp
class XXX {
  // put all axis types you are going to use in the variant
  using axis_t = bh::axis::variant<bh::axis::regular<>, bh::axis::integer<>>;
  using axes_t = std::vector<axis_t>;
  using histogram_t = bh::histogram<axes_t>;
  histogram_t hist_;
};

// in .cpp
XXX x;
x.hist_ = bh::make_histogram(<etc etc>); // as before
jvo203 commented 4 years ago

Thank you.

HDembinski commented 4 years ago

now fixed in develop branch