开发者

Passing parameters for callback function

开发者 https://www.devze.com 2023-02-03 03:55 出处:网络
I have a functionA which takes in two arguments => a callback function and an argument for the callback function. The argument of the callback could be built in type like int or the user defined type.

I have a functionA which takes in two arguments => a callback function and an argument for the callback function. The argument of the callback could be built in type like int or the user defined type. How could I declare the functionA ?

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

The TYPEA could be the built in type or the user defined type. Should I use dynamic_casting in the handler to cast the typeA to appropriate type based on the callback function( in th开发者_Python百科at case, what should typeA be?) or should I use template in this case?


You can pass like this :

#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" );
}


If the function does not use the argument for anything other than for the callback, I would remove the callback completely:

// c++0x, same can be achieved with boost::function/boost::bind in c++03
void function( std::function< void ( void ) > f ) 
{
   f();
}
void callback1( int );
void callback2( Type );
//void callback3( double );
void user_code() {
   function( std::bind( callback1, 5 ) );
   function( std::bind( callback2, Type( 1, 2, 3, 4 ) );
   // function( std::bind( callback3, 5.0 );
}

By using a generic functor (std::function) that only has the arguments (none) passed from inside the function, you are decoupling the function from the callback. Now you can pass any type and it is up to the caller to bind the callback value (i.e. the callback argument is not a responsibility of function, nor function needs to know about it's type or value).


The TYPEA could be the built in type or the user defined type.

I think, you want a function template if the type of argument to the callback-function could be anything!

template<class T>
void function(void (*handler)(T), T variable)
{
   handler(variable);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消