【问题标题】:choose stepper in odeint through if statement通过 if 语句在 odeint 中选择步进器
【发布时间】:2020-02-09 17:11:38
【问题描述】:

我想通过这样的 if 语句选择集成方案:

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

但 stepper 仅在大括号内有效。 在 if 语句之前要定义的步进器类型是什么? 另一种方法是将集成方案(甚至步进器)作为参数传递给函数。

【问题讨论】:

    标签: c++ odeint


    【解决方案1】:

    在 C++17 及以上版本中,为此我们可以应用std::variant,如下所示:

    #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>>;
    

    那么你可以这样做:

    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.
    

    但是虽然我不知道你项目的全部代码,但我想后面的代码不会像上面那样简单。 如果我是你,我会将基本类 stepperBaseeulerrunge_kutta4 定义为 stepperBase 的继承。

    【讨论】:

    • 谢谢。如果我知道要写什么而不是“auto”,我认为这会给我一种更简洁的方式。
    猜你喜欢
    • 2017-08-13
    • 1970-01-01
    • 2021-04-04
    • 2018-08-27
    • 1970-01-01
    • 1970-01-01
    • 2013-03-14
    • 2020-05-14
    • 1970-01-01
    相关资源
    最近更新 更多