C++ 将参数数量未定义的函数传递给类

C++ Passing function with not defined number of arguments to the class

本文关键字:函数 未定义 参数 数数 C++      更新时间:2023-10-16

我正在解决这个问题,我在这里问了另一个问题,但即使在我得到结果之后,我也无法让事情工作。在我们开始之前,我在 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;
}

如果你想看,这是完整的代码:链接

不可以,您只能存储类型已知的数据(在编译时)。

但是,您可以将函数作为参数传递。 函数模板处理各种类型的。

class Sphere {
    public:
        template<typename F>
        void shade(F&& f);
};

例如

void functionA(int) {}
void functionB(double) {}
Sphere sphere;
sphere.shade(functionA);
sphere.shade(functionB);