如何将函数对象传递给期望void *指针的函数?
How can I pass a function object to a function that expects a void * pointer
我有一个函数,它期望被传递给一个函数的普通引用
void func(* pOtherFunc);
我想创建多个函数与轻微的变化和传递那些-我正在考虑的函数对象。我如何将这个函数传递给函数对象?
传统函数指针:
我认为你指向函数的指针没有很好地定义。下面是一个示例:
void test (int a) // first function to be called
{ cout <<"TEST function: "<<a; }
void test2 (int a) // other function to be called
{ cout <<"second test function: "<<a; }
void func( void (*pOtherFunc)(int a) ) // your function
{
cout << "Call: ";
(*pOtherFunc)(10);
cout<<endl;
}
int main(int ac, char**av)
{
func (test);
func (test2);
return 0;
}
如果你想有一个指向你的函数的变量,你可以这样写:
void (*pf)(int a);
pf = test;
func(pf);
如你所见,你的函数指针应该总是有相同的签名;否则,编译器将不知道如何向它们传递参数。
函数对象的替代
另一种选择是使用对象,特别是在函数带有附加参数的情况下。为此,您将需要一个基对象,并且所有其他"函数对象"都应该从基对象派生。
class myFunction {
public:
virtual void myfunc(int a) { cout <<"class function: "<<a<<endl; }
};
class mynewFunction : myFunction {
public:
virtual void myfunc(int a) { cout <<"other class function: "<<a<<endl; }
};
然后可以使用这些类来实例化对象或指向对象的指针:
int main(int ac, char**av)
{
myFunction f;
mynewFunction g;
f.myfunc(10);
g.myfunc(10);
}
当然,您可以将这些对象作为参数传递给其他函数。
代码:
void func(* pOtherFunc );
你不能传递一个函数对象。你可以给它传递一个指向函数的指针。
void func(int(*pf)(int)) { cout << pf(3); }
int f(int x) { return x; }
int g(int x) { return x*x; }
int main() {
cout << "Hello World" << endl;
int (*p1)(int) = (int(*)(int))f;
int (*p2)(int) = (int(*)(int))g;
func(p1);
func(p2);
return 0;
}
传递函数对象需要一个不同的签名
相关文章:
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 在c++类上调用void函数
- 在派生函数中指定void*参数
- C++为什么尽管我调用了void函数,它却不起作用
- 如何从void函数输出字符串
- 为什么这个函数将"const char*"转换为"void* const"而不是"const void*"
- 将尾部调用void(i32,..)位转换为llvm::函数以获取FnAttribute
- 库函数需要一个 std::function<void(void)>,如何传入类函数?
- 如何将指针从一个void函数传递到另一个C++
- 为什么全局函数 void showA(A&x) 能够访问 A 类的私有成员?
- 如何将函数<void()>写入管道/套接字对?
- 错误:无法在没有对象的情况下调用成员函数'void Fortest::run()'|
- 标准的大小::函数<void(int&)>类型
- 如何函数<void(字符串消息)>绑定到成员函数?
- 函数void()返回一个值,而不是char或string
- 函数void QQuickWindow::setDefaultAlphaBuffer(bool useAlpha)的用途
- 错误 LNK2019:函数 "void __cdecl Padding(int)" 中引用未解析的外部符号___iob_func
- 我可以有一个~析构函数(void)吗?
- 函数<void(T)> 带有默认参数的参数
- 错误:参数太少,无法函数"void alpha(std::string*,student)"