我正在处理这个问题,我在这里问了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