c++ - 使用double和long double的C++显式模板实例化。
所以我写了这个模板函数,它是针对浮点的。
在h中
template <typename FloatingPointType>
double nextLow(FloatingPointType a);
在Cpp中
template <typename FloatingPointType>
FloatingPointType nextLow(FloatingPointType a)
{
return std::nextafter(a, std::numeric_limits<FloatingPointType>::lowest());
}
现在我想我可以为所有浮点类型明确地实例化这个函数。
template<> float nextLow<float>(float a);
template<> double nextLow<double>(double a);
template<> long double nextLow<long double>(long double a);
但是在行中
template<> double nextLow<double>(double a);
我从intellisense得到这个
"more than one instance of overloaded function matches the argument list:"
还有编译器的这个
error: ambiguous template specialization ‘nextLow<double>’ for ‘double bricks::nextLow(double)’
39 | template<> double nextLow<double>(double a);
为什么会这样?做 double
和 long double
得到威胁为同一类型?
【回答】:
我在头文件中找到了问题所在。
那里写着。
template <typename FloatingPointType>
double nextLow(FloatingPointType a);
但当然应该是这样
template <typename FloatingPointType>
FloatingPointType nextLow(FloatingPointType a);
还有... <>
需要被删除,否则编译器会在使用模板时发出抱怨。
template<> float nextLow<float>(float a);
template<> double nextLow<double>(double a);
template<> long double nextLow<long double>(long double a);
应该改成这样
template float nextLow<float>(float a);
template double nextLow<double>(double a);
template long double nextLow<long double>(long double a);