kip622
kip622

Reputation: 399

Using min, max within template declarations

Say I have a polynomial class where the degree is controlled by a template, such as the following:

template<int degree>
class Polynomial {
....
}

How can I create an Add function that adds two polynomials of potentially different degrees? Ideally it would be something like

template<int degree1, int degree2>
Polynomial<max(degree1, degree2)> Add(Polynomial<degree1> poly1, Polynomial<degree2> poly2)
{
...
}

Is there a way to do this in c++?

Upvotes: 1

Views: 1208

Answers (3)

PaperBirdMaster
PaperBirdMaster

Reputation: 13320

Use std::min or std::max from the algorithm header:

#include <algorithm>

template<int degree1, int degree2>
Polynomial<std::max(degree1, degree2)> Add(Polynomial<degree1> poly1, Polynomial<degree2> poly2)
{
    // ...
}

Upvotes: 0

jogojapan
jogojapan

Reputation: 69967

In C++11 you can use a constexpr function for this:

constexpr int max(int n1, int n2)
{ return (n1>n2?n1:n2); }

template <int N1, int N2>
Polynomial<max(N1,N2)> add(const Polynomial<N1> &p1, const Polynomial<N2> &p2)
{ return /*...*/ }

Whereas in pre-C++11, there is no concept of constexpr functions, but the ternary conditional operator can still be used directly:

template <int N1, int N2>
Polynomial<(N1>N2?N1:N2)> add(const Polynomial<N1> &p1, const Polynomial<N2> &p2)
{ return /*...*/ }

Upvotes: 2

Marc Glisse
Marc Glisse

Reputation: 7925

template<int degree>
class Polynomial{
...
};

template<int degree1, int degree2>
Polynomial<(degree1<degree2)?degree2:degree1>
Add(Polynomial<degree1> poly1, Polynomial<degree2> poly2)
{
...
}

Upvotes: 1

Related Questions