myfirsttime1 myfirsttime1 - 2 months ago 7
C++ Question

Number type from a polynomial type

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

class can be just
, in which case I want
to be of type
, or other custom polynomial class.

What is a correct way to define this templated function.
I am having trouble writing it properly for the case
polynomial = std::vector<double>

Note: The code above contains some of my guesses of how the type of
and the return type might have to be defined, but they don't seem to be correct.


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 typenames to let the compiler know expressions such as p::value_type are actually types.