|
Boost : |
Subject: Re: [boost] [lclcontext] Any interest in Pythonesque "with-as" statement in C++.
From: Avi Kivity (avi_at_[hidden])
Date: 2015-08-18 04:15:46
On 08/17/2015 11:59 AM, Sam Kellett wrote:
>> I think Python's concept of Context and Context Managers useful and I've
>> adapted, to the best of my abilities, a similar concept in C++. For those
>> not familiar with this concept, I'll quote a brief snippet from the
>> documentation:
>>
>> "Simply stated, this library enables the use of the Pythonesque
>> with-statement construct in C++. More
>> broadly, this library seeks to formalize a generalized version of a subset
>> of the RAII (Resource
>> Acquisition is Initialization) idiom that, for the lack of preexisting
>> terms, I shall refer here to as the
>> STEP (Scope Triggered Event Processing) idiom. The STEP idiom is the
>> commonly occurring use case
>> where for a given block of code some user specified action(s) must execute
>> on entry and on exit, and
>> the failure to do so will result in some deterministic behavior."
>>
>> You can find the library here:
>>
>> https://github.com/m-w-a/WG
>>
>> Documentation is here:
>>
>> https://github.com/m-w-a/WG/tree/master/Local/Docs
>>
>> (In the same repository I've also redid Boost's local_function, but that
>> the subject of another posting.)
>>
>> If there is enough interest from the community for such a library then I
>> will go ahead and "Boostify" it.
>>
> i'm sure you already know this but C++14's initialized lambda captures
> basically are python's with-as (albeit with C++'s normal syntax tax).
>
> struct foo {
> foo() { std::cout << "foo()" << std::endl;
> ~foo() { std::cout << "~foo()" << std::endl;
> };
>
> auto make_foo() -> foo {
> return {};
> }
>
> auto main() -> int {
> std::cout << "before" << std::endl;
> [f = make_foo()]() {
> std::cout << "during" << std::endl;
> }();
> std::cout << "after" << std::endl;
> }
>
> With perfect forwarding we could even achieve a nicer syntax without any
> macros:
>
> with(make_foo(), [](auto f) {
> // ...
> });
>
It's not the same. There is no way to conditionally return from the
enclosing scope from the lambda:
with(make_foo(), [](auto f) {
if (!f) {
return;
}
// ...
});
is different from the python with/as construct.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk