正在返回模板

Returning templates

本文关键字:返回      更新时间:2023-10-16

是否可以返回模板?

这是我一直在尝试的,但没有效果。

template<int degree>
class Polynomial
{
public:
   ... ususal stuff ...
   // Polynimal<degree - 1>
   Polynomial derivative() { /* returns a different template */ }
};

int main()
{
   Polynomial<3> cubic;
   Polynomial<2> parabola;
   parabola = cubic.derivative();
}

这可能吗?我少了什么小金块?

您可以将成员函数作为函数模板:

template<int ret_degree>
Polynomial<ret_degree> derivative() { /* returns a different template */ }

或者,如果你知道返回多项式的次数,你可以这样做:

Polynomial<degree-1> derivative() { /* returns a different template */ }

degree在编译时是已知的,因此您可以在返回类型中使用degree -1作为值参数:

template<int degree>
class Polynomial
{
public:
   Polynomial<degree-1> derivative() 
   {  
         Polynomial<degree-1> d;
         //...
         return d;
   }
};
int main() {
         Polynomial<3> cubic;
         Polynomial<2> parabola;
         parabola = cubic.derivative();
        return 0;
}

演示:http://www.ideone.com/44Pc7

我想你想要这个:

template<int degree>
class Polynomial
{
public:
   ... ususal stuff ...
   // Polynimal<degree - 1>
   Polynomial< degree-1 > derivative() {
     Polynomial< degree-1 > res;
     //assign values
     return res
   }
};

确保在专门化Polynomial<0>时,方法derivative不会退出。