2013-03-12 43 views
1

假設我有一個函數int func(int x, int y, int z),我需要在另一個函數內調用它10次,即int runge(int, ... , int func(int a, int b))。 我知道我可以創建10個功能,即如何從更大的功能創建更小的功能?

int runge1(int a, int b) {return func(1, a, b);} 

不過,我想這樣做的一個簡單的方法。 基本上我想創建一個函數指針作爲這樣的:

for(int i=0; i<10; i++) 
    { 
    //func would have two variables input into it, variable1, variable2 
    int (*func)=func(i, variable1, variable2); 
    } 
+2

見'的boost ::綁定'。 – Morwenn 2013-03-12 14:05:53

+1

對不起,你的關於在另一個函數中調用函數* 10次的例子根本不能說明問題。也許通過擴展更多一些(即對於'i = 1,2,3 ......),你的問題會變得更加清晰。 – 2013-03-12 14:07:49

+0

謝謝你的幫助,抱歉我的問題不清楚。我需要等一會兒才能接受正確答案,但感謝您的幫助。 – 2013-03-12 14:16:10

回答

4

您正在尋找std::bind

std::function<int(int,int)> f = std::bind(&func, i, std::placeholders::_1, std::placeholders::_2); 

這將綁定ifunc第一個參數並留下剩餘的參數綁定。然後,您可以撥打f像這樣:

f(1, 2); 

如果你願意,你可以把你所有的新綁定的功能集成到一個std::vector

using namespace std::placeholders; 
std::vector<std::function<int(int,int)>> funcs; 
for (int i = 0; i < 10; i++) { 
    funcs.push_back(std::bind(&func, i, _1, _2)); 
} 

如果你沒有C++ 11 ,有一個boost::bind副本。

1

我對你的描述不是100%肯定,但它看起來像你希望討好的功能。

在C++中,這裏有一個很好的例子:How can currying be done in C++?

+0

該示例比較舊,而且那些提及的綁定器在新標準中已被廢棄,它們具有'std :: bind'和lambdas。 – 2013-03-12 14:14:06

0

我敢肯定你想知道std::function,lambda表達式也許std::bind

int func(int x, int y, int z); 

typedef std::function<int(int,int)> FuncT; 
std::array<FuncT, 10> functions; //or whatever container suits your needs 
for (int i = 0; i < 10; ++i) 
{ 
    functions[i] = [=](int a, int b) { return func(i,a,b); }; //with lambdas 
    functions[i] = std::bind(func, i, std::placeholders::_1, std::placeholders::_2); //with bind 
} 

(我喜歡lambda表達式,但是這是一個品味的問題...)