[英]template overload of trigonometric functions
I am developing a larger library, where I would like to be able to change the floating point precision used. 我正在开发一个更大的库,在这里我希望能够更改所使用的浮点精度。 Trigonometric functions are used in a number of places, so I decided to include templated wrappers for eg sine and cosine. 在许多地方都使用了三角函数,因此我决定包括例如正弦和余弦的模板包装器。
I have made the following simple example, which gives a stack corruption and I cannot figure out why. 我给出了以下简单示例,该示例给出了堆栈损坏的情况,我无法弄清原因。 Any hints 任何提示
#include <cmath>
#include <iostream>
namespace sps {
template <typename T>
inline T sin(const T& v) { return sin(v); }
template <typename T>
inline T cos(const T& v) { return cos(v); }
template <>
inline float sin<float>(const float& v) { return sinf(v); }
template <>
inline float cos<float>(const float& v) { return cosf(v); }
} // namespace sps
template float sps::sin(const float& v);
template float sps::cos(const float& v);
template double sps::sin(const double& v);
template double sps::cos(const double& v);
int main()
{
double d = 2.0;
std::cout << sps::sin(d) << std::endl; /* (*) */
float f = 2.0f;
std::cout << sps::sin(f) << std::endl;
return 0;
}
If I explicitly state, which functions to use, eg sps::sin(f), I still get a stack corruption. 如果我明确声明要使用的功能,例如sps :: sin(f),我仍然会遇到堆栈损坏的情况。 The stack corruption is thrown in the line with the asterisk (*). 堆栈损坏以星号(*)开头。 If I omit the explicit instantiations, the stack corruption still occurs. 如果我省略显式实例化,则仍会发生堆栈损坏。 I tried changing the inputs to by-value, but this has no effect either. 我尝试将输入更改为按值,但这也不起作用。
I get the same error using gcc 6.3.0 and MSCV 2017. 使用gcc 6.3.0和MSCV 2017我遇到相同的错误。
Thanks in advance Jens 在此先感谢Jens
You are getting an infinit recursion: 您将获得无限递归:
template <typename T>
inline T sin(const T& v) { return sin(v); } // keep calling sin
what you need is to change the return value to: 您需要将返回值更改为:
template <typename T>
inline T sin(const T& v) { return std::sin(v); }
^^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.