2016-02-25 66 views
0

我有執行線搜索算法,例如的this Brent method,我想提出的是通用模板,這將允許我對於優化任何標量函數以一個參數x但我想在error_func這不僅取決於x同時也對其它一些參數堵塞。C++與函數作爲參數函數模板依賴於附加參數

也許(僞)碼會更說明了我想做的事:

一般庫:

typedef double(*scalar_function1D)(double); 

// this function vary "x" in order to make error_func(x) close to zero 
template< scalar_function1D error_func> 
double lineSearch_Brent (double x, double xmin, double xmax, double tol){ 
    double f = error_func(x); 
    while(abs(f)>tol){ 
     f = error_func(x); 
     // body of line search algorithm, details not important 
    } 
    return x; 
} 

具體使用情況:

// we would like to find optimal "x" for this model_error function for given "params" 
double model_error(double x, int n, double * params ... /* many other parameters there */){ 
    // body of specific model for error function which depends on "x" but also on other parameters; details not importaint 
} 

double optimize_x_for_given_model(double xmin, double ymin, int n, double * params){ 
    // how to plug in "params" now ?!? 
    return lineSearch_Brent<model_error>(0.5*(xmin+xmax), xmin, xmax, 1.0e-8); 
} 

明顯的問題model_error不是scalar_function1D型的,因爲它有更多的參數。

我知道這種問題可以通過面向對象編程例如來解決。像這樣:

class Scalar_function1D{ public virtual double eval(double); } // shared interface 

class Model_error : public Scalar_function1D { // specific implementation 
    public: 
    int n; 
    double * params; 
    virtual double eval(double){ 
     // body which depends on "params" 
    }; 
} 

但我想知道如何使用函數模板來做到這一點。

+0

哪裏的誤差函數的其他參數從何而來? –

+0

其他參數指定要優化的問題。例如。考慮我在N維空間中有一個函數,我想在特定的一維線上進行優化。所以'params'將會1)描述要優化的函數的形狀2)指定線條的方向。參數'x'將沿着那條線進行座標。 –

回答

2

不是傳遞一個非類型模板參數:

template< scalar_function1D error_func> 
double lineSearch_Brent (double x, double xmin, double xmax, double tol) { ... } 

只是通過一個任意函數對象:

template <class ScalarFunction1D> 
double lineSearch_Brent (ScalarFunction1D error_func, double x, 
    double xmin, double xmax, double tol) { ... } 

這允許你只是傳遞中,例如,一個lambda捕獲一些其他參數:

lineSearch_Brent([=](double x){ return model_error(x, n, params); }, 
    0.5*(xmin+xmax), xmin, xmax, 1.0e-8); 

或任何適當的。

+0

lambda函數在編譯時解決,可內聯? –

+0

@ProkopHapala是的 – Barry