[TriLUG] OT: A C++ Templated Class Problem

Ed Hill ed at eh3.com
Fri Apr 14 12:52:32 EDT 2006


On Fri, 2006-04-14 at 12:17 -0400, Owen Berry wrote:
> I think you need to inline all your template functions. In other words,
> all your code needs to be in the header file.

Yes, the most general way is to put all the code in the headers and this
is exactly whats done with the STL since all the possible template types
cannot be known until they get instantiated.  A lot of C++ can be
all-headers and no-libs.

Another approach, one that you can use if you know that only a certain
small number of types will always be used, is to compile libraries
containing explicit instantiations.  In that strategy, the headers may
be strictly declaratory such as:

  namespace foo {
    template <class Real> class Bar {
    public:
        Bar();
        ~Bar();
        other_funcs();
    private:
        //  ...data...
    };
  }

and then separate files may contain the actual template code plus the
necessary explicit instantiations such as:

  namespace foo {
    template class Bar<float>;
    template class Bar<double>;
  }

which are then compiled to produce libraries.  I mention this explicit
instantiation strategy since its commonly used for C++ where there is a
lot of mathematical work being done and there are often only a few
appropriate numerical types available.  Your "matrix" code might be a
good fit.

Ed

-- 
Edward H. Hill III, PhD
office:  MIT Dept. of EAPS;  Rm 54-1424;  77 Massachusetts Ave.
             Cambridge, MA 02139-4307
emails:  eh3 at mit.edu                ed at eh3.com
URLs:    http://web.mit.edu/eh3/    http://eh3.com/
phone:   617-253-0098
fax:     617-253-4464




More information about the TriLUG mailing list