代码之家  ›  专栏  ›  技术社区  ›  Chris

C++:std::bind->std::function

  •  -1
  • Chris  · 技术社区  · 6 年前

    我有几个函数接收以下类型:

    function<double(int,int,array2D<vector<double *>>*)>
    

    哪里 array2D 是自定义类型。此外,我有一个函数,它将以下内容作为参数:

    double ising_step_distribution(double temp,int i,int j,array2D<vector<double *>>* model)
    

    现在,为了绑定第一个值, temp ,并返回一个具有正确签名的函子,我在写:

    double temp = some_value;
    function<double(int,int,array2D<vector<double *>>*)> step_func = 
        [temp](int i, int j, array2D<vector<double *>>* model){
            return ising_step_distribution(temp,i,j,model);
        }
    }
    

    这是可行的。但是,以下中断:

    auto step_func = 
        [temp](int i, int j, array2D<vector<double *>>* model){
            return ising_step_distribution(temp,i,j,model);
        }
    }
    

    出现以下错误:

    candidate template ignored: 
    could not match 
    'function<double (int, int, array2D<vector<type-parameter-0-0 *, allocator<type-parameter-0-0 *> > > *)>' 
    against 
    '(lambda at /Users/cdonlan/home/mcmc/main.cpp:200:25)'
    void mix_2D_model(function<double(int,int,array2D<vector<T*>>*)> step_distribution_func,...
    

    因此,代码束是丑陋的、模糊的和重复的(因为我正在制作许多这样的代码)。


    我一直在阅读文档,我理解我应该能够写:

    function<double(int,int,array2D<vector<double *>>*)> step_func = 
        bind(ising_step_distribution,temp,_1,_2,_3);
    

    然而 只有 我看到的示例是类型为的函数 function<void()> . 此操作失败并出现错误:

    // cannot cast a bind of type 
    // double(&)(double,int,int,array2D<vector<double *>>*) 
    // as function<double(int,int,...)
    

    如何获得视觉上干净的绑定和投射?

    1 回复  |  直到 6 年前
        1
  •  3
  •   Maxim Egorushkin    6 年前

    如何获得视觉上干净的绑定和投射?

    一种方法是:

    using F = function<double(int,int,array2D<vector<double *>>*)>;
    auto step_func = 
        [temp](int i, int j, array2D<vector<double *>>* model){
            return ising_step_distribution(temp,i,j,model);
        }
    }
    

    然后:

    auto step_func_2 = F(step_func);
    mix_2D_model(step_func_2, ...);
    

    或:

    mix_2D_model(F(step_func), ...);