On 9/1/13 5:45 PM, Ross Boylan wrote:
> Some .hpp files look more like .cpp files in that they have a lot of
> implementation code in them, e.g., stanc_helper.hpp. Is there a reason
> for that?
Yes and no.
With template classes and functions, there's not a clean way
to separate headers and implementations. There's a great
discussion in Vandevoorde and Josuttis's book on C++ Templates (really
THE book on template programming in C++).
If you look at Eigen and Boost, the libs on which we're based,
you'll see they're almost exclusively header only. This means there
are NO implementation files, just header files.
> It may not make any practical difference (though it may explain some of
> the long compile times), but I'm just trying to understand what's going
> on.
The long compile times are from all the template metaprogramming
and evaluation going on in Eigen and in our auto-diff lib.
> One possible rationale is that the files are going into an include
> directory, at least for rstan. But there are already a bunch of .cpp
> files that go there, so that doesn't seem to be it.
>
> Some C++ compilers might also react badly to having the same code
> compiled in more than one place.
You have to be careful to only ever compile a definition in a single
translation unit.
Now having said all this, Vandevoorde and Josuttis also show you how
to divide the code up so that you have three kinds of files:
foo.hpp (headers only)
foo_def.hpp (headers with defs)
foo_inst.cpp (instantiations)
This way you strip the headers down to just headers with only
declarations and no function definitions. The _def.hpp is what
you see in header-only template libs. You can include those and
use them header only and ignore the _inst.cpp files.
Then _inst.cpp has instantiations, which says
which instantiations of the templates to compile into object code.
You can compile these ahead of time and then use the headers .hpp
files, but only for instantiations of templates you prespecified in
_inst.cpp.
The plan is to move more of Stan to this style of code, but we
have a big problem in that some of our template instantation patterns
are huge. For instance, the Student-t distribution function has
hundreds of instantiations (vectorization plus auto-diff inside
the arg structure with free choices leading to horrible combinatorics).
- Bob