利用注册类实现特定类型匹配函数模板

177 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。 ​

 函数模板可以让不同的类型调用功能相同的代码,可以减少代码的冗余,但是如果只想让特定类型使用函数模板呢?可以利用模板特化和注册类实现。

代码如下:

#include <iostream>

template <typename T>
struct Register{};

template <>
struct Register<int> {
  typedef int Type;
  constexpr static const char* TypeName = "int";
};

template <>
struct Register<float> {
  typedef float Type;
  constexpr static const char* TypeName = "float";
};

template <>
struct Register<long> {
  typedef long Type;
  constexpr static const char* TypeName = "long";
};

template <typename T, typename = typename Register<T>::Type>
void print(const T& x) {
  std::cout << Register<T>::TypeName << '\t' << x << std::endl;
}

int main() {
  print(-1);
  print(2147483650);
  print(12.11);  // double类型,不匹配
  return 0;
}

所有向Register注册过的类型,都可以匹配成功print函数,未向Register注册过的类型在编译时就会报错,报错信息如下: