C++ 模板使用

C++模板博大精深。

函数模板

缺省模板类型

看代码。

1
2
auto LIH = labelInputs.getHandle<int64_t>();
auto IIH = imageInputs.getHandle<>();

其中labelInputsimageInputsClass Tensor的instances。
函数声明如下。

1
2
3
4
5
6
7
/// \return a new handle that points and manages this tensor.
template <class ElemTy = float> Handle<ElemTy> getHandle() &;

template <class ElemTy = float> const Handle<ElemTy> getHandle() const &;

/// If Tensor is rvalue, it is an error to get its Handle.
template <class ElemTy = float> Handle<ElemTy> getHandle() && = delete;

上面的示例设置了模板参数默认的类型。因此IIH的默认是float类型。
此外,我们还可以了解到:

  1. 模板参数可以作为类型(函数返回类型或者参数类型),类模板的模板参数(如上面代码的Handle<ElemTy>)。
    其中类模板Handle的声明为template <class ElemTy> class Handle final {...};
  2. 模板类的显示实例化(explicit instantiation)和隐式实例化(implicit instantiation)
    以一个示例来说明。假定我们声明了函数模板
    1
    2
    3
    4
    template <class T>
    T GetMax (T a, T b) {
    return (a>b?a:b);
    }

显式实例化
我们可以像”重复声明“那样,告诉编译器要做的实例化工作。切记的是,实例化发生在编译期间。显式实例化就是主动告诉编译器如何实例化。

1
2
3
int x,y;
GetMax<int>(int, int);
GetMax <int> (x,y);

隐式实例化
隐式实例化就是在函数调用处,编译时由编译器自己推断应该如何实例化。

1
2
int i,j;
GetMax (i,j);

类模板

类模板的显示和隐式实例化
显式实例化可以这样

1
2
3
template <class ElemTy> class Handle final {...};
template class Handle<float>;
template class Handle<double>;