exprtk_simple_example_05.cpp 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /*
  2. **************************************************************
  3. * C++ Mathematical Expression Toolkit Library *
  4. * *
  5. * Simple Example 5 *
  6. * Author: Arash Partow (1999-2020) *
  7. * URL: http://www.partow.net/programming/exprtk/index.html *
  8. * *
  9. * Copyright notice: *
  10. * Free use of the Mathematical Expression Toolkit Library is *
  11. * permitted under the guidelines and in accordance with the *
  12. * most current version of the MIT License. *
  13. * http://www.opensource.org/licenses/MIT *
  14. * *
  15. **************************************************************
  16. */
  17. #include <cstdio>
  18. #include <string>
  19. #include "exprtk.hpp"
  20. template <typename T>
  21. struct myfunc : public exprtk::ifunction<T>
  22. {
  23. using exprtk::ifunction<T>::operator();
  24. myfunc()
  25. : exprtk::ifunction<T>(2)
  26. { exprtk::disable_has_side_effects(*this); }
  27. inline T operator()(const T& v1, const T& v2)
  28. {
  29. return T(1) + (v1 * v2) / T(3);
  30. }
  31. };
  32. template <typename T>
  33. inline T myotherfunc(T v0, T v1, T v2)
  34. {
  35. return std::abs(v0 - v1) * v2;
  36. }
  37. template <typename T>
  38. void custom_function()
  39. {
  40. typedef exprtk::symbol_table<T> symbol_table_t;
  41. typedef exprtk::expression<T> expression_t;
  42. typedef exprtk::parser<T> parser_t;
  43. const std::string expression_string =
  44. "myfunc(sin(x / pi), otherfunc(3 * y, x / 2, x * y))";
  45. T x = T(1);
  46. T y = T(2);
  47. myfunc<T> mf;
  48. symbol_table_t symbol_table;
  49. symbol_table.add_variable("x",x);
  50. symbol_table.add_variable("y",y);
  51. symbol_table.add_function("myfunc",mf);
  52. symbol_table.add_function("otherfunc",myotherfunc);
  53. symbol_table.add_constants();
  54. expression_t expression;
  55. expression.register_symbol_table(symbol_table);
  56. parser_t parser;
  57. parser.compile(expression_string,expression);
  58. const T result = expression.value();
  59. printf("Result: %10.5f\n",result);
  60. }
  61. int main()
  62. {
  63. custom_function<double>();
  64. return 0;
  65. }