Skip to content

Instantly share code, notes, and snippets.

@yuikns
Last active August 29, 2015 14:09
Show Gist options
  • Save yuikns/b4e009c176ae7fc8dc4f to your computer and use it in GitHub Desktop.
Save yuikns/b4e009c176ae7fc8dc4f to your computer and use it in GitHub Desktop.
// Copyright 2014 Yu Jing<[email protected]>
#include <stdio.h>
#include <map>
using std::map;
class Opol {
private:
class Agent {
public:
Agent(Opol & m_o, int m_k) : o(m_o), k(m_k) {}
// The operator int() allows implicit and explicit casting to ints.
// This means that when the CB functionality cannot be applied,
// it tries if it works for an int (implicit) and you can directly
// cast a Agent object to an int value (by using int(x), (int)x,
// dynamic_cast<int>(x) or static_cast<int>(x)).
// ref: http://www.cplusplus.com/forum/beginner/33566/
operator int() const {
printf("get : %d <- %d\n", k, o.get(k));
return o.get(k);
}
void operator = (int v) {
printf("set : %d -> %d\n", k, v);
o.set(k, v);
}
int operator++() {
printf("pre-increment\n");
o.set(k, o.get(k) + 1);
return *this;
}
int operator++(int) {
printf("post-increment\n");
int val = o.get(k);
o.set(k, val + 1);
return val;
}
private:
Opol &o;
int k;
};
public:
int get(int k) const {
return a.at(k);
}
void set(int k, int v) {
if (a.find(k) == a.end()) {
a.insert(std::pair<int, int>(k, v));
} else {
a[k] = v;
}
}
Agent operator[] (int k) {return Agent(*this, k);}
private:
map<int, int> a;
};
int main(int argc, char * argv[]) {
Opol o;
o[1] = 3;
printf("o_1 is : %d\n", static_cast<int>(o[1]));
printf("o_1++ is : %d\n", static_cast<int>(o[1]++));
printf("++o_1 is : %d\n", static_cast<int>(++o[1]));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment