2

I want to choose integration scheme through a if statement like this:

//stepper_type steppr; ??
if (integration_scheme == "euler") {
    [auto] stepper = euler<state_type>{};
}
else
{
    [auto] stepper = runge_kutta4<state_type>{};
}

but stepper is only valid inside the curly bracket. What is the type of stepper to be defined before the if statement? another way is to pass the integration scheme (or even stepper) as an argument to a function.

Abolfazl
  • 1,047
  • 2
  • 12
  • 29

1 Answers1

1

In C++17 and over, for this purpose we can apply std::variant as follows:

#include <variant>

class state_type {};

template<class T>
class euler {};

template<class T>
class runge_kutta4 {};

template<class T>
using stepper_t = std::variant<euler<T>, runge_kutta4<T>>;

Then you can do like this:

DEMO

stepper_t<state_type> stepper;

if (integration_scheme == "euler") {
    stepper = euler<state_type>{};
}
else{
    stepper = runge_kutta4<state_type>{};
}

std::cout << stepper.index(); // prints 0.

But although I don't know the whole code of your project, I think the subsequent code would not be simple one in the above way. If I were you, I will define the base calss stepperBase and euler and runge_kutta4 as the inheritances of stepperBase.

Hiroki
  • 2,780
  • 3
  • 12
  • 26