pythonwithステートメントに似たものをC++で実装しようとしています。主にQt-OpenGLで使用する予定なので、メソッドはbind
and 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;
};
cpp:
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;
}
質問:
- 必要と少し不器用
class A
に感じます。class B
より良い代替案はありますか? &&
代わりに使用することの欠点はあり&
ますか?一時的なオブジェクトの使用が可能になります(例With w(X(), y);
)