pse*_*vin 6 c++ templates header-files
我在TFRuntime.h中有一个函数
class TFRuntime {
...
template <typename T>
Status computeXYSlice(Volume<T>* input, int zCoord, Volume<T> *output);
...
}
Run Code Online (Sandbox Code Playgroud)
TFRuntime.cpp包括tensorflow库头,例如
#include <tensorflow/cc/ops/standard_ops.h>
#include <tensorflow/cc/saved_model/loader.h>
Run Code Online (Sandbox Code Playgroud)
我不想在标题中包含这些包含,因为这会强制任何使用TFRuntime的人也包含它们.但是,如果我希望该computeXYSlice函数允许任何类型,我必须在.h文件中包含该实现.然而,该实现需要上面提到的tensorflow头.
我该如何解决这个问题?我可以明确地"实例化"该computeXYSlice函数的某些变体吗?例如,在T是float或int或double?或者,还有更好的方法?
我可以只显式地"实例化"computeXYSlice函数的某些变体吗?例如,哪里T是浮点数还是整数或双数?
你可能,他们的实现不需要在标题中.我马上就会谈到这一点.但是如果你真的想要允许任何类型,那么你的模板必须在标题中.就是这样.
如果您希望仅支持一小组类型,作为模板实例化,而不进行重载(有时在执行查找时可能会有所不同),则标准具有显式模板实例化的机制.
你的标题看起来像这样......
class TFRuntime {
public:
template <typename T>
Status computeXYSlice(Volume<T>* input, int zCoord, Volume<T> *output);
};
Run Code Online (Sandbox Code Playgroud)
...而你的实现文件,将包含显式的instatiation 定义,如此......
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>*);
Run Code Online (Sandbox Code Playgroud)
您必须包含显式实例化定义,否则您的程序格式错误,无需诊断.除非在某处出现显式实例化,否则必须在发生隐式实例化时定义模板函数.
这有点麻烦.但是如果你的最终目标是确实有一堆实例化(而不是重载),那就是你将它们联系在一起的方式.