C++ 将参数数量未定义的函数传递给类
C++ Passing function with not defined number of arguments to the class
我正在解决这个问题,我在这里问了另一个问题,但即使在我得到结果之后,我也无法让事情工作。在我们开始之前,我在 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);
相关文章:
- 2个模板化类的非模板友元函数未定义引用错误
- C++:在共享对象中调用抽象基类构造函数/未定义的符号
- 获取线函数未定义错误。无法在字符串中保存可验证的内容
- 链表复制构造函数 |未定义的行为
- 尝试使用 std::函数(未定义的符号)声明模板化类状态时出现链接错误
- 专用纯虚拟模板函数(未定义引用)的另一个问题
- 可视化C++ strtoull 函数未定义
- 绑定C++中的C函数(未定义的引用)
- 函数未定义引用c++
- C++构造函数未定义的引用
- 在同一语句中调用的执行 IO 的函数:未定义或未指定
- 在参数中接受 2 个类的友元函数 - 未定义'Class'
- c++ CreateWindow()函数未定义
- 使用c++中的haskell函数:未定义引用错误
- c++模板变量函数未定义引用
- OpenGL函数未定义glow
- C/ c++未使用的内联函数未定义的引用
- 调用从不兼容类型强制转换的零数据结构的成员函数-未定义
- Cocos2d-x Box2D CContactListener构造函数未定义
- 包括Boost网络库使Windows.h函数未定义