myfirsttime1 - 1 year ago 136

C++ Question

I am writing some templated functions for polynomials.

They will input a polynomial, e.g.

`template<typename polynomial>`

auto evaluate(polynomial const& pol, polynomial::value_type x ) -> dectype(pol[0])

{

// return Horner-Ruffini

};

The

`polynomial`

`std::vector<T>`

`x`

`T`

What is a correct way to define this templated function.

I am having trouble writing it properly for the case

`polynomial = std::vector<double>`

`x`

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

You should probably put some more thinking into the constraints on type `p`

(i.e. is it acceptable to assume a `value_type`

member etc.), but this works for your `std::vector`

case:

```
#include <vector>
#include <iostream>
template<typename p>
typename p::value_type evaluate(p const& pol, typename p::value_type x) {
typename p::value_type result = 0;
for (const auto& v : pol) {
result = result * x + v;
}
return result;
}
int main() {
std::vector<double> test{1, 2, 3, 4};
std::cout << evaluate(test, 5.0) << std::endl;
}
```

You are missing a few `typename`

s to let the compiler know expressions such as `p::value_type`

are actually types.

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**