我正在尝试使用模板元编程实现正弦函数。但是,由于 cv-qualification 冲突,我收到错误“radtest”不是 double & 的有效模板参数。这是代码:
#include <iostream>
using namespace std;
template <double&, int, int> struct
Series;
template <double& rad> struct Sine
{
enum
{
maxterms=10
};
static inline double sin()
{
return (rad) *
Series<(rad), 0, maxterms>::val();
}
};
template <double& rad, int i, int
maxterms> struct Series
{
enum
{
cont = i+1 != maxterms,
nxt1 = (i+1)*cont,
nxtmax = maxterms*cont
};
// uses recursive definition of
// Sine
// sin(x)=x*term(0)
// term(n)=1-
// x*x/(2*n+2)/(2*n+3)*term(n+1)
static inline double val()
{
return 1 - (rad)*
(rad)/(2.0*i+2.0)/(2.0*i+3.0)
* Series<rad * cont, nxt1,
nxtmax>::val();
}
};
#define SineT(rad) Sine<rad>::sin()
constexpr double radtest=0.707;
int main()
{
cout << "Sine of " << radtest
<< " is: " << SineT(radtest);
return 0;
}
可能是什么问题?提前致谢。
最佳答案
问题是 radtest
是 const
(由 constexpr
暗示)所以你不能有 double&
参数sine
绑定(bind)到它。
如果你尝试让它成为 double radtest
(不是 constexpr),或者如果你尝试让所有模板参数成为 const double&
那么你会遇到另一个问题:你无法绑定(bind)临时引用非类型模板参数。标准明确不允许这样做:
§ 14.3.2 Template non-type arguments
A template-argument for a non-type template-parameter shall be a converted constant expression (5.20) of the type of the template-parameter. For a non-type template-parameter of reference or pointer type, the value of the constant expression shall not refer to (or for a pointer type, shall not be the address of):
- ...
- (1.2) a temporary object (12.2),
- ...
我个人看不出有什么办法可以解决这个问题。这(使用引用作为模板非类型参数)确实突破了 C++ 模板系统的功能范围。
我可以推荐的是只创建一个 constexpr
sin 函数。
关于c++ - 模板元编程,cv-qualification 错误中的冲突,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43996755/