A Discrete-Event Network Simulator
API
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
main-callback.cc
Go to the documentation of this file.
1 /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
2 #include "ns3/callback.h"
3 #include "ns3/assert.h"
4 #include <iostream>
5 
6 using namespace ns3;
7 
8 static double
9 CbOne (double a, double b)
10 {
11  std::cout << "invoke cbOne a=" << a << ", b=" << b << std::endl;
12  return a;
13 }
14 
15 class MyCb {
16 public:
17  int CbTwo (double a) {
18  std::cout << "invoke cbTwo a=" << a << std::endl;
19  return -5;
20  }
21 };
22 
23 
24 int main (int argc, char *argv[])
25 {
26  // return type: double
27  // first arg type: double
28  // second arg type: double
30  // build callback instance which points to cbOne function
31  one = MakeCallback (&CbOne);
32  // this is not a null callback
33  NS_ASSERT (!one.IsNull ());
34  // invoke cbOne function through callback instance
35  double retOne;
36  retOne = one (10.0, 20.0);
37  // callback returned expected value
38  NS_ASSERT (retOne == 10.0);
39 
40  // return type: int
41  // first arg type: double
43  MyCb cb;
44  // build callback instance which points to MyCb::cbTwo
45  two = MakeCallback (&MyCb::CbTwo, &cb);
46  // this is not a null callback
47  NS_ASSERT (!two.IsNull ());
48  // invoke MyCb::cbTwo through callback instance
49  int retTwo;
50  retTwo = two (10.0);
51  // callback returned expected value
52  NS_ASSERT (retTwo == -5);
53 
54  two = MakeNullCallback<int, double> ();
55  // invoking a null callback is just like
56  // invoking a null function pointer:
57  // it will crash.
58  //int retTwoNull = two (20.0);
59  NS_ASSERT (two.IsNull ());
60 
61 #if 0
62  // The below type mismatch between CbOne() and callback two will fail to
63  // compile if enabled in this program.
64  two = MakeCallback (&CbOne);
65 #endif
66 
67 #if 0
68  // This is a slightly different example, in which the code will compile
69  // but because callbacks are type-safe, will cause a fatal error at runtime
70  // (the difference here is that Assign() is called instead of operator=)
72  three.Assign (MakeCallback (&CbOne));
73 #endif
74 
75  return 0;
76 }
Callback template class.
Definition: callback.h:924
bool IsNull(void) const
Check for null implementation.
Definition: callback.h:1018
#define NS_ASSERT(condition)
At runtime, in debugging builds, if this condition is not true, the program prints the source file...
Definition: assert.h:61
void Assign(const CallbackBase &other)
Adopt the other's implementation, if type compatible.
Definition: callback.h:1159
static double CbOne(double a, double b)
Definition: main-callback.cc:9
Callback< R > MakeCallback(R(T::*memPtr)(void), OBJ objPtr)
Definition: callback.h:1242
int main(int argc, char *argv[])
int CbTwo(double a)