I am looking for an elegant solution for implementing the equivalent of the C# using statement in C++. Ideally the resultant syntax should be simple to use and read.
C# Using statement details are here - http://msdn.microsoft.com/en-us/library/yh598w02(v=vs.80).aspx
I am not sure whether the solution would be to use function pointers with destructors on classes, some form of clever template programming or even meta template programming. Basically I do not know where to start with this...
You don't need to implement this in C++ because the standard pattern of RAII already does what you need.
When the block scope ends,
myfile
is destroyed which closes the file and frees any resources associated with the object.The reason the
using
statement exists in C# is to provide some syntactic sugar around try/finally andIDisposable
. It is simply not needed in C++ because the two languages differ and the problem is solved differently in each language.