c++ - 为回调函数传递参数

标签 c++

我有一个 functionA,它接受两个参数 => 一个回调函数和一个回调函数的参数。回调的参数可以建立在像 int 这样的类型或用户定义的类型中。我怎么能声明 functionA ?

eg:
void functionA(void (*handler)(TYPEA), TYPEA variableA)
{
  *handler(variableA);
}

TYPEA 可以是内置类型或用户定义类型。我应该在处理程序中使用 dynamic_casting 来根据回调函数将 typeA 转换为适当的类型(在这种情况下,typeA 应该是什么?)还是应该在这种情况下使用模板?

最佳答案

你可以这样传递:

#include <iostream>

template< typename A, typename B >
void foo( A a, B b )
{
    a( b );
}

void boo1( const int p )
{
    std::cout<<"boo( " << p << " )" << std::endl;
}

void boo2( const std::string p )
{
    std::cout<<"boo( " << p << " )" << std::endl;
}


int main()
{
    foo( boo1, 3 );
    foo( boo2, "abc" );
}

关于c++ - 为回调函数传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4644409/

相关文章:

c++ - 有没有办法在每个源文件中自动复制#define

c++ - 在 Eclipse 中构建后没有二进制文件

c++ - istringstream 十进制整数输入为8位类型

c++ - Win32 设备事件 : Not receiving DBT_DEVTYP_VOLUME on DBT_DEVICEARRIVAL event

c++ - OpenGL 项目需要 DirectX 库文件

c++ - 运算符 string() { some code } 做什么?

c++ - C++ 中的虚函数困境

c++ - CImg 的库名称是什么?

c++ - 哪个Qt库包含QApplication

c++ - va_copy -- 移植到 Visual C++?