tau*_*ran 10 c++ python with-statement state-management
我试图用 C++中的语句实现类似python的东西.正如我打算使用它主要使用Qt的OpenGL的方法被调用bind,并release(在python __enter__,__exit__).
我提出的代码:
标题:
#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;
};
Run Code Online (Sandbox Code Playgroud)
CPP:
With::~With()
{
for (auto it = a.begin(); it != a.end(); ++it)
{
delete *it;
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
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;
}
Run Code Online (Sandbox Code Playgroud)
问题:
class A和class B感觉有点笨拙.还有更好的选择吗?&&而不是&?这将使临时对象的使用成为可能(例如With w(X(), y);)Joh*_*erg 10
with语句是python中的一种方法,它已经是C++中的常见内容.它被称为RAII:资源获取是初始化.
在python中,当创建一个类对象时,该__init__方法被调用(但这不是严格的保证).__del__垃圾收集器在对象不再使用后的某个时刻调用该方法,但它不是确定性的.
在C++中,析构函数在定义良好的点调用,因此不需要with.
我建议你只使用类似B类的东西(不需要A类或With类).
template <typename T>
class B {
public:
B(T& t) : m_t(t){
m_t.bind();
}
~B() {
m_t.release();
}
T& m_t;
}
Run Code Online (Sandbox Code Playgroud)
像这样用它:
{
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
Run Code Online (Sandbox Code Playgroud)