作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我的模板特化不起作用。有谁知道如何使用模板正确实现此功能?
template<class T>
float hz_to_nsec(const T &freq) {
return freq != 0 ? static_cast<float>(NSEC_PER_SEC) / freq : 0;
}
template <>
double hz_to_nsec<double>(const double &freq) {
return freq != 0 ? static_cast<double>(NSEC_PER_SEC) / freq : 0;
}
最佳答案
特化和主模板的返回类型必须匹配:
template<class T>
float hz_to_nsec(const T &freq) {
return freq != 0 ? static_cast<float>(NSEC_PER_SEC) / freq : 0;
}
template <>
float hz_to_nsec<double>(const double &freq) {
^^^^^
return freq != 0 ? static_cast<float>(NSEC_PER_SEC) / freq : 0;
^^^^^
}
或者,您可以提供重载而不是模板特化:
template<class T>
float hz_to_nsec(const T &freq) {
return freq != 0 ? static_cast<float>(NSEC_PER_SEC) / freq : 0;
}
double hz_to_nsec(const double &freq) {
return freq != 0 ? static_cast<double>(NSEC_PER_SEC) / freq : 0;
}
关于c++ - 由于未知的模板定义,模板特化失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34644351/
关闭。这个问题不符合Stack Overflow guidelines .它目前不接受答案。 我们不允许提问寻求书籍、工具、软件库等的推荐。您可以编辑问题,以便用事实和引用来回答。 关闭 4 年前。
正如您在 this travis.yml 中看到的那样文件,我的代码依赖于一些第三方库,我在构建项目之前将它们安装在远程系统上。 Travis 每次推送提交时都会下载并构建这些库,这可以避免吗?我的意
我是一名优秀的程序员,十分优秀!