ns-3 Manual, Release ns-3-dev
2. callback instantiation: a way to instantiate a template-generated forwarding callback which can forward any calls
to another C++ class member method or C++ function.
This is best observed via walking through an example, based on samples/main-callback.cc.
Using the Callback API with static functions
Consider a function:
static double
CbOne(double a, double b)
{
std::cout << "invoke cbOne a=" << a << ", b=" << b << std::endl;
return a;
}
Consider also the following main program snippet:
int main(int argc, char
*
argv[])
{
// return type: double
// first arg type: double
// second arg type: double
Callback<double, double, double> one;
}
This is an example of a C-style callback – one which does not include or need a this pointer. The function template
Callback is essentially the declaration of the variable containing the pointer-to-function. In the example above,
we explicitly showed a pointer to a function that returned an integer and took a single integer as a parameter, The
Callback template function is a generic version of that – it is used to declare the type of a callback.
Note: Readers unfamiliar with C++ templates may consult http://www.cplusplus.com/doc/tutorial/templates/.
The Callback template requires one mandatory argument (the return type of the function to be assigned to this
callback) and up to five optional arguments, which each specify the type of the arguments (if your particular callback
function has more than five arguments, then this can be handled by extending the callback implementation).
So in the above example, we have a declared a callback named “one” that will eventually hold a function pointer. The
signature of the function that it will hold must return double and must support two double arguments. If one tries to
pass a function whose signature does not match the declared callback, a compilation error will occur. Also, if one
tries to assign to a callback an incompatible one, compilation will succeed but a run-time NS_FATAL_ERROR will
be raised. The sample program src/core/examples/main-callback.cc demonstrates both of these error cases
at the end of the main() program.
Now, we need to tie together this callback instance and the actual target function (CbOne). Notice above that CbOne
has the same function signature types as the callback– this is important. We can pass in any such properly-typed
function to this callback. Let’s look at this more closely:
static double CbOne(double a, double b) {}
^ ^ ^
| | |
| | |
Callback<double, double, double> one;
You can only bind a function to a callback if they have the matching signature. The first template argument is the
return type, and the additional template arguments are the types of the arguments of the function signature.
14 Chapter 2. Simulator