Have a template method but not expose implementation

  • A+
Category:Languages

I have a function in TFRuntime.h

class TFRuntime { ...     template <typename T>     Status computeXYSlice(Volume<T>* input, int zCoord, Volume<T> *output); ... } 

TFRuntime.cpp includes tensorflow library headers such as

#include <tensorflow/cc/ops/standard_ops.h> #include <tensorflow/cc/saved_model/loader.h> 

I do not want to make these includes in the header since that would force anyone using TFRuntime to include them as well. However if i want the computeXYSlice function to allow any type, I have to include the implementation in the .h file. The implementation however requires the above mentioned tensorflow headers.

How do I get around this problem? Could I explicitly 'instantiate' only certain variants of the computeXYSlice function? E.g., where T is float or int or double? Or is there a better way?

 


Could I explicitly 'instantiate' only certain variants of the computeXYSlice function? E.g., where T is float or int or double?

You may, and their implementation need not be in the header. I'll get to that in a moment. But if you really want to allow any type then your template must be in a header. That's just how it is.

If you wish to support only a small set of types, as template instantiations, without overloading (can make a difference sometimes when doing lookup), the standard has a mechanism for explicit template instantiation.

Your header will look something like this...

class TFRuntime { public:     template <typename T>     Status computeXYSlice(Volume<T>* input, int zCoord, Volume<T> *output); }; 

... And your implementation file, will contain the explicit instatiation definitions, like so...

template <typename T> Status TFRuntime::computeXYSlice(Volume<T>* input, int zCoord, Volume<T> *output) {   // Implement it }  template Status TFRuntime::computeXYSlice(Volume<int>*, int, Volume<int>*);  template Status TFRuntime::computeXYSlice(Volume<double>*, int, Volume<double>*); 

You have to include the explicit instantiation definitions, otherwise your program is ill-formed, no diagnostic required. The template function must be defined when implicit instantiation occurs, unless an explicit instantiation appears somewhere.

This is a bit cumbersome. But if your end goal is to indeed have a bunch of instantiations (as opposed to overloads), that's how you tie it all together.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: