【问题标题】:C++ Passing function with not defined number of arguments to the classC ++将未定义参数数量的函数传递给类
【发布时间】:2016-06-14 13:31:17
【问题描述】:

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

【问题讨论】:

  • 请提供minimal, complete, and verifiable example。我们需要您尝试失败的特定代码。
  • 我编辑了帖子,仅供参考,我正在尝试为类的每个对象分配不同的特征函数。我将使用它为我的光线追踪器创建可编程着色器,现在可以正常工作了。显然我不能发布整个事情,它太长了。但我希望我发布的代码对您有所帮助。谢谢。
  • “显然我无法发布整个内容” MCVE,那么我们可以帮助您修复它。我不知道你的问题是什么——你给了我们一个Sphere 类,它的构造函数接受一个参数,但你试图用三个参数构造它们。我不知道你想做什么。
  • 嗯,实际上我很确定这就是它的全部内容。我忘了从 sp1 中删除其他参数,但无论如何这都不是问题。该程序运行良好。如果我完成此操作并且在返回某种数据类型时遇到问题,我会发布整个代码。我将在一个更大的项目中使用它,但我在这个小部分有问题。基本上我的目标是在构造时为每个对象分配一个不同的函数,然后用相同的名称调用它们。像 obj1.Shader() 会运行 func1() 而 obj2.Shader() 会运行 func2()

标签: c++ function class pointers reference


【解决方案1】:

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

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

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

例如

void functionA(int) {}
void functionB(double) {}

Sphere sphere;

sphere.shade(functionA);
sphere.shade(functionB);

【讨论】:

  • 谢谢,但能详细解释一下吗?我还听说模板不利于性能。谢谢。
猜你喜欢
  • 1970-01-01
  • 2018-08-28
  • 1970-01-01
  • 2011-05-06
  • 1970-01-01
  • 2015-09-23
  • 2015-10-11
  • 2013-09-21
  • 1970-01-01
相关资源
最近更新 更多