c++ - 模板元编程,cv-qualification 错误中的冲突

标签 c++ template-meta-programming

我正在尝试使用模板元编程实现正弦函数。但是,由于 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;
}

可能是什么问题?提前致谢。

最佳答案

问题是 radtestconst(由 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/

相关文章:

c++ - boost::asio::async_read_until 不调用处理程序

c++ - 在 std::list 中就地创建自定义类型对象

c++ - 如何检测类型是否可以流式传输到 std::ostream?

c++ - 可以接受函数指针或 Functor 的模板参数

c++ - 在 lambda 比较器中使用捕获

c++ - 我们应该在 C++17 及更高版本中使用临时对象的生命周期延长吗?

c++ - OpenCL C++ 绑定(bind) : How to implement a callback for enqueueWriteBuffer competition

c++ - 将多个参数传递给流运算符

c++ - 如何检测具有特定签名的静态成员函数的存在?

c++ - 如何编写用于选择函数的样板代码