fork download
  1. // Example program
  2. #include <iostream>
  3. #include <string>
  4.  
  5. #include <tuple>
  6. #include <functional>
  7.  
  8. template<typename... Fn>
  9. class LinearCombination {
  10. public:
  11. template<typename... Un>
  12. LinearCombination(Un&&... fs)
  13. : functions(std::forward<Un>(fs)...)
  14. {
  15. coefs.fill(0.0);
  16. }
  17.  
  18. double operator()(double x) const
  19. {
  20. return evaluateImpl(x, std::integral_constant<size_t, sizeof...(Fn) - 1>());
  21. }
  22.  
  23. void setCoef(size_t i, double c)
  24. {
  25. coefs[i] = c;
  26. }
  27.  
  28. private:
  29. template<size_t I>
  30. double evaluateImpl(double x, std::integral_constant<size_t, I> index) const
  31. {
  32. return evaluateOne(x, index) + evaluateImpl<I - 1>(x, std::integral_constant<size_t, I - 1>());
  33. }
  34.  
  35. template<size_t I>
  36. double evaluateImpl(double x, std::integral_constant<size_t, 0> index) const
  37. {
  38. return evaluateOne(x, index);
  39. }
  40.  
  41. template<size_t I>
  42. double evaluateOne(double x, std::integral_constant<size_t, I>) const
  43. {
  44. auto coef = coefs[I];
  45. return coef == 0.0 ? 0.0 : coef * std::get<I>(functions)(x);
  46. }
  47.  
  48.  
  49. std::tuple<Fn...> functions;
  50. std::array<double, sizeof...(Fn)> coefs;
  51. };
  52.  
  53. template<typename... Fn>
  54. auto make_linear_combination(Fn&&... fn)
  55. {
  56. return LinearCombination<Fn...>{std::forward<Fn>(fn)...};
  57. }
  58.  
  59. double A(double)
  60. {
  61. return 1.0;
  62. }
  63.  
  64. /// Integration 1.0
  65. double integrate3D(double (*f)(double, double, double))
  66. {
  67. return f(1, 2, 3);
  68. }
  69.  
  70. struct YHelper {
  71. static double Y(double x, double y, double z)
  72. {
  73. return (f(x+y) - f(x)) * (f(y+z) - f(y)) * A(z+y);
  74. }
  75.  
  76. static std::function<double(double)> f;
  77. };
  78.  
  79. std::function<double(double)> YHelper::f;
  80.  
  81.  
  82. /// Integration 2.0
  83. template<typename Integrable>
  84. double integrate3D_2(Integrable&& f)
  85. {
  86. return f(1, 2, 3);
  87. }
  88.  
  89. int main()
  90. {
  91. auto f1 = [](double x) { return x; };
  92. auto f2 = [](double x) { return 2 *x; };
  93.  
  94. auto lc = make_linear_combination(std::move(f1), std::move(f2));
  95. lc.setCoef(0, 1.0);
  96. lc.setCoef(1, -1.0);
  97.  
  98. std::cout << lc(2.0) << "\n";
  99.  
  100. YHelper::f = std::ref(lc);
  101. std::cout << integrate3D(&YHelper::Y) << "\n";
  102.  
  103. auto Y = [&lc](double x, double y, double z) { return (lc(x+y) - lc(x)) * (lc(y+z) - lc(y)) * A(z+y); };
  104. std::cout << integrate3D_2(Y) << "\n";
  105. }
  106.  
Success #stdin #stdout 0s 3460KB
stdin
Standard input is empty
stdout
-2
6
6