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 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
#include <iostream>
#include <functional>
#include <cstdio>
#include <string>
struct foo
{
void display() { std::cout << "foo::display()\n" ; history += " display," ; }
void display2( int a, double b )
{ std::cout << "foo::display2(" << a << ',' << b << ")\n" ; history += " display2," ; }
std::string history = "call history:" ;
};
struct bar
{
template < typename CALLABLE, typename... ARGS >
decltype(auto) call_it( CALLABLE&& fn, ARGS&&... args ) const
noexcept( std::is_nothrow_invocable<CALLABLE,ARGS...>::value )
{
std::cout << "bar::call_it => " ;
// https://en.cppreference.com/w/cpp/utility/functional/invoke (C++17)
// https://en.cppreference.com/w/cpp/utility/forward
return std::invoke( std::forward<CALLABLE>(fn), std::forward<ARGS>(args)... ) ;
}
};
int main()
{
foo object ;
const bar b ;
b.call_it( std::puts, "hello there!" ) ; // call non-member function
// call member functions
b.call_it( &foo::display, object ) ;
b.call_it( &foo::display2, object, 2345, 67.89 ) ;
b.call_it( &std::ostream::write, std::cout, "abcdefgh\n", 9 ) ;
// use a lambda expression (call a closure object)
b.call_it( []( auto&& x ) { std::cout << x << '\n' ; }, "hello again!" ) ;
// access a (public) member variable!
std::cout << b.call_it( &foo::history, object ) << '\n' ;
// call a function object
std::cout << b.call_it( std::plus<>{}, std::string("bye "), "for now!" ) << '\n' ;
}
| |