Functionality of multiple operator overloading

May 28, 2008 at 12:56am
I just needed to know if it was possible to overload [] and += simultaneously for a same context

more precisely, I created a class called callback which basically holds the pointers to a function or to a class method and I wish to use it to build my own event-driven objects in a framework... so far things work well, I just wondered how I would make

void dummy1(void) {
std::cout << "dummy1" <<std::endl;
}

void dummy2(void) {
std::cout << "dummy2" <<std::endl;
}

void dummy3(void) {
std::cout << "dummy3" <<std::endl;
}

module["onInit"] += callback(dummy1);
module["onThis"] += callback(dummy2);
module["onThat"] += callback(dummy3);
module["onThis"] -= callback(dummy2);
module.raiseEvent("onThis");

where it would output absolutely nothing

What should I do?

Thanks in advance
May 28, 2008 at 6:07am
You can do that by returning a reference to an object from the [] operator, where the += operator is implemented. Example structure:

1
2
3
4
5
6
7
8
9
10
11
class Handle;

class Module {
public:
  Handle& operator[](const std::string& str);
};

class Handle {
public:
  Handle& operator+=(callback c);
};


Usage:
1
2
3
4
Handle& h = module["onInit"];
h += callback(dummy1);
// or combined into one line:
module["onInit"] += callback(dummy1);
Last edited on May 28, 2008 at 6:09am
Topic archived. No new replies allowed.