gpt4 book ai didi

c++ - 由于未知的模板定义,模板特化失败

转载 作者:太空狗 更新时间:2023-10-29 23:26:19 24 4
gpt4 key购买 nike

我的模板特化不起作用。有谁知道如何使用模板正确实现此功能?

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com