-2

So, in the answer of this question Proper way close WinAPI HANDLEs (avoiding of repeated closing) the answerer creates a HandleWrapper template, which you can use like this:

HandleWrapper<KernelHandleTraits> hFile(CreateFile(...))

and hFile will be destroyed when it gets out of scope.

In your code there also may be lines similar to this:

ReadFile(hFile(), ...)

I am wondering how the template or class for a Handle would look like, if I wanted to use it like this:

ReadFile(hFile, ...)

Note the missing parenthesis. Is there any C++ trick to achieve this?

Community
  • 1
  • 1
J. Doe
  • 73
  • 9

1 Answers1

1

Yes, there is: You would have to implement a conversion operator, i.e. operator HANDLE(), that returns the stored handle.*

Nothing I'd recommend. There's enough invisible code in C++ already. No need to add to it, less so when there is so little to be had.


* Incidentally, the code you linked to already implements the appropriate conversion operator, operator traits::HandleType(). In other words: You don't need to implement anything in particular to use your favored syntax.
IInspectable
  • 46,945
  • 8
  • 85
  • 181
  • Okaay. I have got mixed up the conversion operator with the function (functor) operator.. – J. Doe Feb 25 '17 at 20:47
  • @J.Doe: A `HANDLE` is trivially copy-constructible, and passed by value into the `ReadFile()` call. No copy-c'tor is executed. The destructor runs, when `hFile` goes out of scope. – IInspectable Feb 25 '17 at 20:52
  • What if CreateFile returned a bool instead of a handle. And the handle would be stored in a pointer to a handle. Something like this: if (CreateFile(&handle, "filename", ...)) {..} in this case how could I use the "nice" syntax? – J. Doe Mar 07 '17 at 13:59
  • @J.Doe: A function that takes a pointer to a handle usually does so, because that **is** the return value. In that case you need to pass a pointer to a plain handle, and attach a resource management object once it returns. RAII wrappers often provide an `attach()` member for that, or have a constructor taking a handle value. The implementation you linked to has neither, and you would have to extend it. – IInspectable Mar 07 '17 at 14:02