
Untitled
By: a guest on
Aug 12th, 2012 | syntax:
None | size: 1.75 KB | hits: 8 | expires: Never
Python with statement in C
#include <iostream>
#include <vector>
class With
{
public:
class A
{
public:
virtual ~A() { }
};
template <typename T>
class B : public A
{
public:
B(T& _t) : t(_t)
{
t.bind();
}
virtual ~B()
{
t.release();
}
T& t;
};
template <typename... Args>
With(Args&... args)
{
set(args...);
}
~With();
template <typename T, typename... Args>
void set(T& t, Args&... args)
{
set(t);
set(args...);
}
template <typename T>
void set(T& t)
{
a.push_back(dynamic_cast<A*>(new B<T>(t)));
}
std::vector<A*> a;
};
With::~With()
{
for (auto it = a.begin(); it != a.end(); ++it)
{
delete *it;
}
}
class X
{
public:
void bind() { std::cout << "bind x" << std::endl; }
void release() { std::cout << "release x" << std::endl; }
};
class Y
{
public:
void bind() { std::cout << "bind y" << std::endl; }
void release() { std::cout << "release y" << std::endl; }
};
int main()
{
X y;
Y y;
std::cout << "start" << std::endl;
{
With w(x, y);
std::cout << "with" << std::endl;
}
std::cout << "done" << std::endl;
return 0;
}
template <typename T>
class B {
public:
B(T& _t) : t(_t){
t.bind();
}
~B() {
t.release();
}
T& t;
}
{
B<X> bound_x(x); // x.bind is called
B<Y> bound_y(y); // y.bind is called
// use x and y here
} // bound_x and bound_y is destroyed here
// so x.release and y.release is called
struct X {
X() { std::cout << "bindn"; }
~X() { std::cout << "releasen"; }
};
int main() {
X x;
}