Advertisement
sebbu

calcul formel

Apr 14th, 2017
287
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. #include <iostream>
  2. #include <unordered_map>
  3. #include <cmath>
  4.  
  5. namespace ast {
  6.  
  7. typedef std::unordered_map<char, double> data;
  8.  
  9. #pragma STDC FENV_ACCESS ON
  10.  
  11. template<int D> struct val {
  12.     double operator() (const data&) const { return D; }
  13. };
  14. template<char I> struct mis {
  15.     double operator()(const data& v) const { return v.at(I); }
  16. };
  17. template<typename Expr> struct minus {
  18.     double operator()(const data& v) const { return -(Expr()(v));  }
  19. };
  20. template<typename Expr1, typename Expr2> struct add {
  21.     double operator()(const data& v) const { return Expr1()(v)+Expr2()(v);  }
  22. };
  23. template<typename Expr1, typename Expr2> struct sub {
  24.     double operator()(const data& v) const { return Expr1()(v)-Expr2()(v);  }
  25. };
  26. template<typename Expr1, typename Expr2> struct mul {
  27.     double operator()(const data& v) const { return Expr1()(v)*Expr2()(v); }
  28. };
  29. template<typename Expr1, typename Expr2> struct div {
  30.     double operator()(const data& v) const { return Expr1()(v)/Expr2()(v); }
  31. };
  32. template<typename Expr1, typename Expr2> struct mod {
  33.     double operator()(const data& v) const { return fmod(Expr1()(v),Expr2()(v)); }
  34. };
  35.  
  36. }
  37.  
  38. using namespace ast;
  39.  
  40. int main() {
  41.     add<
  42.         mis<'a'>,
  43.         mul<
  44.             val<2>,
  45.             mis<'b'>
  46.         >
  47.     > expression;
  48.  
  49.     mod<mis<'a'>, mis<'b'> > exp2;
  50.     double a=1, b=2; //or whatever
  51.     std::cout << expression({ { 'a', a }, { 'b', b } }) << '\n';
  52.     a=7, b=3;
  53.     std::cout << exp2({ { 'a', a }, { 'b', b } }) << '\n';
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement