我正在處理這個問題,我在這裏問了this other question,但即使在我得到結果後,我也無法得到工作。在我們開始之前,我在C中使用了指針來傳遞函數,但是我對C++來說比較新,而指針不能傳遞未知參數的函數。C++傳遞函數的參數數量沒有定義
我的問題是:
我如何得到一個函數傳遞到一類,而不必知道有多少論點沒有考慮。如果我想提供我想綁定到課程中的功能,我應該怎麼做?喜歡的東西:
ac ac1(args_of_the_object, a_function_with_its_arguments)
我在類初始化列表綁定功能的工作,感謝的人誰幫助,
function<void()> sh = bind(&hard_coded_function_name, argument);
並創建一個類的對象時,我可以設置參數:
class_name(type ar) : argument(ar) {};
你明白了。事情是,我無法將這個功能本身傳遞給班級。我嘗試使用這個與類初始化列表略作修改:
class_name cl1(args, bind(&func_i_want, arguments));
但它導致堆棧轉儲錯誤。
謝謝!
編輯:(那時評論太長)
#include <iostream>
#include <cmath>
#include <limits>
#include <vector>
#include <functional>
using namespace std;
void diffuse(float k){
cout << " WP! " << k;
}
class Sphere{
public:
function<void()> sh;
Sphere (function<void()> X) : sh(X) {};
//another try
function<void()> sh;
Sphere (void (*f)(float)) : sh(bind(&f, arg)) {}; // This is not what I want obviously still I tried it and it doesn't work either.
void Shader(){
sh();
}
};
Color trace(vector<Sphere>& objs){
// find a specific instance of the class which is obj in this case
// Basically what I'm trying to do is
// assigning a specific function to each object of the class and calling them with the Shader()
obj.Shader();
// Run the function I assigned to that object, note that it will eventually return a value, but right now I can't even get this to work.
}
int main() {
vector<Sphere> objects;
Sphere sp1(bind(&diffuse, 5));
Sphere sp1(&diffusea); // I used this for second example
objects.push_back(sp1);
trace(objects);
return 0;
}
這裏是整個代碼,如果你想看到:LINK
請提供[最小的,完整的,並且覈查示例](http://www.stackoverflow.com/help/mcve)。我們需要您嘗試失敗的特定代碼。 – Barry
我編輯了這篇文章,並且我正在嘗試爲該類的每個對象分配一個不同的特徵函數。我打算用它爲我的光線跟蹤器創建可編程着色器,它現在可以正常工作。很顯然,我無法發佈整件事情,因爲這太長了。但我希望我發佈的代碼能夠幫助你。謝謝。 –
「顯然我無法發佈整個事情」< - 這是問題。將示例縮減爲[MCVE](http://www.stackoverflow.com/help/mcve),*然後*我們可以幫助您修復它。我無法分辨你的問題在這裏 - 你給了我們一個'Sphere'類,它帶有構造函數,它帶有一個參數,但你試圖用三個參數構造它們。我不知道你在做什麼。 – Barry