myfirsttime1 - 7 months ago 47

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`

Answer

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.