C++ Logo

std-proposals

Advanced search

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

From: Vaibhav Parate <vaibhavparate321_at_[hidden]>
Date: Sat, 22 Mar 2025 12:25:25 +0530
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 06:55:37