C++ Logo

std-proposals

Advanced search

Re: [std-proposals] Proposal Idea: with Block for C++ – Extending Object Scope

From: Tiago Freire <tmiguelf_at_[hidden]>
Date: Sat, 22 Mar 2025 07:55:04 +0000
It's not unnecessary verbosity, it expresses exactly what you mean without having to think about convoluted interpretation rules about things that appear on multiple lines that might not even be visible on screen.

void foo()

void bar (A a, A& b) with (a, b) {
foo();
}

Does this mean:
a.foo()?
b.foo()?
::foo()?

Notice that it is very clear when I write what I want explicitly.
At some point being too lazy is bad.


________________________________
From: Std-Proposals <std-proposals-bounces_at_[hidden]> on behalf of Vaibhav Parate via Std-Proposals <std-proposals_at_[hidden]>
Sent: Saturday, March 22, 2025 7:55:43 AM
To: std-proposals_at_[hidden] <std-proposals_at_[hidden]>
Cc: Vaibhav Parate <vaibhavparate321_at_[hidden]>
Subject: [std-proposals] Proposal Idea: with Block for C++ – Extending Object Scope

Hello,
Before I spend time on a formal paper for this idea, I want some feedback and suggestions.

Idea:
I'd like to propose a with block for C++ that allows extending the scope of objects, making field access easier and reducing redundant qualifiers.

Motivation (while working on some personal projects):
Currently, in C++, working with objects often requires repeatedly qualifying fields with object-> or object. inside functions and lambdas. This leads to unnecessary verbosity, especially when dealing with deeply nested structures.

Example:
C++ Currently (It is readable but very quickly gets messy, specially when you are the author of the entire codebase):
void foo (A a, B* b, C& c) { // let's assume A, B, and C are types
a.doSomething();
b->doSomethingElse();
// some other calles
c.trySomethingElse();
}

C++ with "with" blocks:
void foo (A a, B* b, C& c) {
with (a, *b, c) {
doSomething();
doSomethingElse();
// some other calles
trySomethingElse();
}
}

Or if you want to use them for the entire function? Consider this:
void foo (A a, B* b, C& c) with (a, *b, c) {
doSomething();
doSomethingElse();
// some other calles
trySomethingElse();
}

What about field name collisions?
They can be easily solved using existing syntax of using object. or object->.

Maybe it will be harder for people to port old code that uses "with" as an identifier (variable name etc.) what about that?
It's not necessary to use this exact keyword, it can be something else like "using" which is already a keyword.

Why?
I always find it annoying to use qualifiers while initializing objects, yeah there are constructors (and other initializers), but there are sometimes where constructors aren't enough and the object needs to be initialized in different ways. I may be wrong here and maybe the only one facing these issues, but does it hurt to have this feature?


Received on 2025-03-22 07:55:07