2012-05-03 50 views
2

我想在特定情況下使用函數指針。我使用的是功能foo用以下原型如何將C++函數指針作爲參數傳遞給一些固定值?

foo(double (*func)(double,double)); 

我可以叫foo正常方式:

double bar(double x, double y) { 
    //stuff 
}; 

int main(void) { 
    foo(bar); 
    return 0; 
}; 

但我想凍結,以獲得相當於一個功能的xdouble (*func)(double)這樣的:

foo(bar(x,double)) 

是否在C++中存在一個類似的語法?

+3

查看'std :: bind'。您可以將值綁定到函數中的一個或多個參數。 – chris

+0

非常感謝,我會檢查一下。 – vanna

+1

如果你沒有支持'std :: function'和'std :: bind'的C++ 11支持,並且在''中找到佔位符,那麼你可以使用Boost等價物。 – AJG85

回答

1

如果您有C++ 11,則可以使用std::bind。下面這個例子,通過動作迅速地將5每個元素轉換一個向量:

#include <iostream> 
using std::cout; 

#include <functional> 
using std::plus; 
using std::bind; 
using std::placeholders::_1; 

#include <vector> 
using std::vector; 

#include <algorithm> 
using std::transform; 

int main() 
{ 
    vector<int> v {1, 3, 6}; 

    //here we bind the value 5 to the first argument of std::plus<int>() 
    transform (v.begin(), v.end(), v.begin(), bind (plus<int>(), _1, 5)); 

    for (int i : v) 
     cout << i << ' '; //outputs "6 8 11" 
} 

至於你的榜樣,我能寫這樣的東西接近它:

#include <iostream> 
using std::cout; 

#include <functional> 
using std::bind; 
using std::function; 
using std::placeholders::_1; 

void foo (function<double (double, double)> func) //take function object 
{ 
    //try to multiply by 3, but will do 2 instead 
    for (double i = 1.1; i < 5.6; i += 1.1) 
     cout << func (i, 3) << ' '; 
} 

double bar (double x, double y) 
{ 
    return x * y; 
} 

int main() 
{ 
    foo (bind (bar, _1, 2)); 
} 

輸出:

2.2 4.4 6.6 8.8 11 

我可能有過於複雜的東西,雖然。這實際上是我第一次同時使用std::bindstd::function

2

如果你不想使用std::bind/std::function,這裏有兩種選擇。

假設你的編譯器支持轉換無國籍的lambda發揮作用的指針,你可以使用lambda綁定x

void foo(double (*f)(double, double)) { (*f)(3.14159, 2.71828); } 

double bar(double x, double y) { return x * y; }; 

int main() 
{ 
    foo([](double x, double y) -> double { return bar(1.0, y); }); 
    return 0; 
} 

或者你甚至可以改變foo到接受任意函數對象的模板。這樣你就可以使用帶有捕獲的lambda:

template<typename TFunc> 
void foo(TFunc f) { f(3.14159, 2.71828); } 

double bar(double x, double y) { return x * y; }; 

int main() 
{ 
    double fixedprm = 1.0; 
    foo([fixedprm](double x, double y) -> double { return bar(fixedprm, y); }); 
    return 0; 
} 
相關問題