Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template Instantiation for Library Use

Tags:

c++

templates

I'm building an image processing library in C++(0x) which relies heavily upon templates, and I'm worried about the effect these templates will have on users' compilation times. For example, I have defined my image class as ns::Image, and I have several pixel types such as ns::PixRGB, ns::PixRGBA, ns::PixHSV, etc...

I will also many image processing functions, e.g.

template<class T, class S>
  void ns::drawCircle(ns::Image<T> & img, S color, ns::Circle);

Now, I know that 95% of users will just want to call ns::drawCircle<PixRGB<byte>, PixRGB<byte>>(...), so I would like to explicitly instantiate just some combinations of these types of functions while still allowing the compiler to custom compile anything that I haven't specified. Doing so will allow me to keep the compilation speed of a shared library and the flexibility of a header-only library.

Is this type of thing possible, and if so what is the syntax?

like image 980
rcv Avatar asked Mar 18 '11 17:03

rcv


1 Answers

This is called an explicit instantiation. In a header file, somewhere after the ns::drawCircle<T,S> function template has been defined:

namespace ns {
    extern template void drawCircle<>(
        Image<PixRGB<byte> >& img, PixRGB<byte> color, Circle);
}

In a *.cpp file in your library:

namespace ns {
    template void drawCircle<>(
        Image<PixRGB<byte> >& img, PixRGB<byte> color, Circle);
}
like image 81
aschepler Avatar answered Sep 22 '22 07:09

aschepler