Reputation:
Is it possible to return a template?
This is what I've been trying, but this isn't working.
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();
}
Is this possible? What little nugget am I missing?
Upvotes: 2
Views: 129
Reputation: 361482
degree
is known at compile time, so you can use degree -1
as value argument in the return type:
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;
}
Demo : http://www.ideone.com/44Pc7
Upvotes: 4
Reputation: 64223
I assume that you want this :
template<int degree>
class Polynomial
{
public:
... ususal stuff ...
// Polynimal<degree - 1>
Polynomial< degree-1 > derivative() {
Polynomial< degree-1 > res;
//assign values
return res
}
};
Make sure that in you specialization for Polynomial<0>
the method derivative
doesn't exits.
Upvotes: 3
Reputation: 76828
You can make the member-function a function template:
template<int ret_degree>
Polynomial<ret_degree> derivative() { /* returns a different template */ }
Or, if you know the degree of the return-polynomial, you can do something like this:
Polynomial<degree-1> derivative() { /* returns a different template */ }
Upvotes: 6