Passing parameters to the callback function

I have a function A that takes two arguments => a callback function and an argument for a callback function. The callback argument can be constructed in an int type or a user type. How can I declare function A?

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

TYPEA can be a built-in type or a user-defined type. Should I use dynamic_casting in the handler to cast type A to the appropriate type based on the callback function (in this case, what should typeA be?) Or use a template in this case?

+3
source share
3 answers

You can go this way:

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

- , , :

// 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 );
}

(std::function), (none) function, . , bind (.. function, function ).

+2

TYPEA can be inline or custom type.

I think you need a function template if the argument type of the callback function can be anything!

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

Source: https://habr.com/ru/post/1784475/


All Articles