明确实例化具有泛型类型的功能模板

时间:2019-04-18 17:48:59

标签: c++ templates explicit-instantiation

我对C ++模板没有太多经验,因此我的术语可能不正确。请多多包涵,欢迎纠正。

我具有通用类型fixed_buf<N>

// in foo.h
template <int N>
class fixed_buf {
 private:
  unsigned char data[N];
 public:
  const unsigned char* begin() const {
    return std::begin(data);
  }

  const unsigned char* end() const {
    return std::end(data);
  }
};

我想定义一个通用的to_hex函数

// in foo.h
template <typename T> std::string to_hex(const T& b);

// in foo.cpp
template <typename T> string to_hex(const T& b) {
  string r;
  hex(b.begin(), b.end(), back_inserter(r));
  return r;
}

我也使用显式实例化:

// in foo.cpp
template string to_hex(const vector<unsign char>&);

如何使用to_hex显式实例化fixed_buf<N>?有可能吗?

1 个答案:

答案 0 :(得分:1)

“明确实例化”

这意味着告诉编译器从功能模板创建具有某些指定类型的功能,即使可能不需要(例如,能够与其链接或减少编译时间)。

模板可以看作是“类型级别功能”。您的to_hex采用某种类型作为参数,然后“返回”某种类型的函数。

to_hex :: T -> to_hex<T>

您的fixed_buf也是类型级别的函数。它需要一些(编译时类型级别)整数,并返回(结构)类型:

fixed_buf :: int(N) -> fixed_buf<N>

您不能将fixed_buf传递给to_hex;它不是类型,而是类型级别的函数。您只能传递fixed_buf的结果。如果您不知道要传递给fixed_buf的(类型级别)整数,则需要将其转换为(类型级别)函数:

\N -》 to_hex(fixed_buf(N)) :: int(N) -> to_hex<fixed_buf<N>>

如果没有某些指定的类型级别整数,则该类型不是;编译器只能实例化类型(在这种情况下,=完全应用的模板)。

因此,您可以显式实例化to_hex<fixed_buf<42>>(这是一个函数),而不是to_hex<fixed_buf<N>>(模板)。

您可以显式实例化to_hex<fixed_buf<1>>to_hex<fixed_buf<2>>等。但我认为这样做不合理


如果您不是要实例化而是“专长”,那么您也不能提供模板专长,因为它需要是部分专长(您不知道N),而这些并不是允许使用功能。解决方案:

  • 将实现放入模板struct中;它们可以部分专门化。

  • 使用重载:

    template <int N>
    string to_hex(const fixed_buf<N>& b) { /* implementation */ }
    

    这是可以正常工作的重载(不是部分专业化;功能模板不允许使用这些重载)。