【问题标题】:C++ template specialization for floating points浮点的 C++ 模板特化
【发布时间】:2018-05-24 16:02:21
【问题描述】:

我想为浮点类型专门化 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文件末尾显式实例化模板类,这样我们就可以在cpp文件中做模板代码了。

【问题讨论】:

  • 您不应该在头文件和 cpp 文件中拆分模板:stackoverflow.com/questions/495021/…
  • 错误消息看起来像您的 X::bucket_width 声明不包含您在定义中添加的 enable_if 部分。
  • @RonKluth 如何将 enable_if 部分正确添加到声明中?

标签: c++ templates c++17 template-specialization specialization


【解决方案1】:

有人可以向我解释我缺少什么吗?

错误说明:

.../x.cpp:46:56: 错误:'X::bucket_width' 的外联定义的返回类型与声明中的不同

也就是说,函数被声明为返回T,但您将其定义为返回std::enable_if_t&lt;std::is_floating_point_v&lt;T&gt;, T&gt;。那些不匹配并且需要。

更一般地说,您尝试做的是部分专门化函数模板,这是不可能的。

这里一个简单的解决方案是使用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;
  }
};

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-06
    相关资源
    最近更新 更多