浮点的 C++ 模板特化

C++ template specialization for floating points

我想专门针对浮点类型的 class X 方法。 以下代码编译并完美运行:

x.hpp:

template <typename T>
class X {
 public:
  ...
  T bucket_width(const BucketID index) const;
  T bucket_min(const BucketID index) const;
  T bucket_max(const BucketID index) const
  ...
};

x.cpp:

...

template <typename T>
T X<T>::bucket_width(const BucketID index) const {
  return bucket_max(index) - bucket_min(index) + 1;
};

template <>
float X<float>::bucket_width(const BucketID index) const {
  return bucket_max(index) - bucket_min(index);
};

template <>
double X<double>::bucket_width(const BucketID index) const {
  return bucket_max(index) - bucket_min(index);
};

...

现在,与此类似 answer 我将 cpp 文件更改为:

template <typename T>
T X<T>::bucket_width(const BucketID index) const {
  return bucket_max(index) - bucket_min(index) + 1;
};

template <typename T>
std::enable_if_t<std::is_floating_point_v<T>, T> X<T>::bucket_width(const BucketID index) const {
  return bucket_max(index) - bucket_min(index);
};

不幸的是,这会导致以下编译器错误:

.../x.cpp:46:56: error: return type of out-of-line definition of 'X::bucket_width' differs from that in the declaration
std::enable_if_t<std::is_floating_point_v<T>, T> X<T>::bucket_width(const BucketID index) const {
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~                       ^

有人可以向我解释我错过了什么吗?
提前致谢!

编辑:我们在cpp文件末尾显式实例化模板classes,这样我们就可以在cpp文件中做模板代码了

Can someone explain to me what I am missing?

错误解释:

.../x.cpp:46:56: error: return type of out-of-line definition of 'X::bucket_width' differs from that in the declaration

也就是说,该函数声明为 return a T,但您将其定义为 return a std::enable_if_t<std::is_floating_point_v<T>, T>。那些不匹配并且需要。

更一般地说,您要做的是部分特化函数模板,这是不可能的。

一个简单的解决方案是使用 if constexpr:

template <typename T>
T X<T>::bucket_width(const BucketID index) const {
  if constexpr (std::is_floating_point_v<T>) {
    return bucket_max(index) - bucket_min(index);
  } else {
    return bucket_max(index) - bucket_min(index) + 1;
  }
};