1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
#include <iostream>
double foo( int a, double b ) { std::cout << "foo( " << a << ", " << b << " )\n" ; return a+b ; }
double bar( int a, double b ) { std::cout << "bar( " << a << ", " << b << " )\n" ; return a*b ; }
using fn_type = double( int, double ) ; // type of the function
double foobar( fn_type& fn /* reference to function */, int arg1, double arg2 )
{ std::cout << "foobar => " ; return fn(arg1, arg2 ) ; }
// polymorphic version of the above
template < typename FN, typename... ARGS > auto generic_foobar( FN&& fn, ARGS&&... args )
{ std::cout << "generic_foobar => " ; return std::forward<FN>(fn)( std::forward<ARGS>(args)... ) ; }
const char* baz( int a, char b, double c )
{ std::cout << "baz( " << a << ", " << b << ", " << c << " )\n" ; return "baz" ; }
int main()
{
foobar( foo, 1, 2.34 ) ;
foobar( bar, 5, 6.78 ) ;
generic_foobar( bar, 5, 6.78 ) ;
generic_foobar( baz, 9, 'A', 1.23 ) ;
generic_foobar( []( auto v ) { std::cout << "closure(" << v << ")\n" ; return v ; }, 1234 ) ;
}
|