- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想为浮点类型特化类 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文件中做模板代码。
最佳答案
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
也就是说,函数被声明为返回一个T
。但您将其定义为返回 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;
}
};
关于浮点的 C++ 模板特化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50513684/
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 4 年前。
正如您在 this travis.yml 中看到的那样文件,我的代码依赖于一些第三方库,我在构建项目之前将它们安装在远程系统上。 Travis 每次推送提交时都会下载并构建这些库,这可以避免吗?我的意
我是一名优秀的程序员,十分优秀!