Generic Function Pointer |
An os_function is a generic
function pointer class which can be specified with up to ten template
parameters. The first template argument specifies the class which the function
is a member of. If the function is not a member of any class or is a static
member, then os_no_member should be used. The
second template argument specifies the return type. The remaining template
arguments are optional. An os_function can
encapsulate functions, static methods, regular methods, or constant methods. If
the function operator is invoked on an os_function
before its function pointer is set, then an exception will be thown.
The following example illustrates the usefulness of the os_function
class. Four generic function pointers are created. One referencing a
function, one referencing a method, one for masquerading as another objects
method, and one to illustrate safety.
#include <iostream>
#include <string>
#include <ospace/helper.h>
void print( os_string str )
{
cout << "using print function to print: " << str << endl;
};
class adder
{
public:
adder() : num_( 0 ) {}
void add( int num )
{
num_ += num;
cout << "my num is now: " << num_ << endl;
}
int num_;
};
template< class Function >
class aggregator
{
public:
aggregator( Function func ) : func_( func ) {}
Function func_;
};
int
main()
{
try
{
os_function< os_no_object, void, os_string > f1( &print );
f1( "hello" );
adder addr;
addr.add( 1 );
os_function< adder, void, int > f2( &addr, &adder::add );
f2( 2 );
aggregator< os_function< adder, void, int > >
aggregate
(
os_function< adder, void, int >( &addr, &adder::add )
);
aggregate.func_( 3 );
os_function< os_no_object, void > f4;
f4();
}
catch ( os_helper_toolkit_error& e )
{
cout << "Caught os_helper_toolkit_error : " << endl;
cout << '\t' << e.what() << endl;
cout << '\t' << e.description( e.code() ) << endl;
}
return 0;
}
using print function to print: hello
my num is now: 1
my num is now: 3
my num is now: 6
Caught os_helper_toolkit_error :
function object does not reference a function or method
Invalid function call.
Copyright©1994-2026 Recursion
Software LLC
All Rights Reserved - For use by licensed users only.