C++ Logo


Advanced search

Introducing abbreviated anonymous struct

From: Desmond Gold <desmondbongcawel922_at_[hidden]>
Date: Thu, 1 Jul 2021 15:20:02 +0800
- This proposal is intended to be a possible alternative to local classes
but with extended specifications.

[ capture-list ] <template param> requires-clause specifiers : inheritance
-> { class scope, public by default }

The syntax is very similar to lambda expression (for the meantime).
However, the arrow is required before the body of the abbreviated anonymous

For instance:
void func() {
  using new_type = [] -> { int x; };
  new_type instance { .x = 10 };
  std::cout << instance.x << '\n'; // prints 10

will be equivalent into:

struct __anon_xx {
  int x;
void func() {
  using new_type = __anon_xx;
  new_type instance { .x = 10 };
  std::cout << instance.x << '\n'; // prints 10

Where __anon_xx is a unique name that is similar to lambdas.

Abbreviated anonymous struct would also support templates, but this will be
a special case of `using` type alias when dealing with abbreviated
anonymous struct.

void func() {
  using new_type = []<typename T> -> {};
  using ok = new_type<int>;

will be equivalent into:

template <typename T> struct __anon_xx {};
void func() {
  using new_type_int = __anon_xx<int>;
  using ok = new_type_int;

Inside the brackets, you can capture a local variable or initialize it to
create an inline static variable, constant by default. soon... (or may be
discarded if the capture-list is not needed).

The type of the abbreviated struct is anonymous even when using a `using`
type alias.

Final Abbreviated Anonymous Struct
[] final -> {};

Constexpr Abbreviated Anonymous Struct might associate with the `constexpr`
class proposal
[] constexpr -> {};

Abbreviated Anonymous Struct may also inherit other classes:
[] : type_1, type_2, type_N -> {};

An abbreviated anonymous class may be defined in function scope, namespace
scope, global scope, etc.

We can also invoke the constructor immediately:
[] -> {}{}.

[] -> { int x, y; } { .x = 10, .y = 3 }

Problems as of now (on this proposed feature):
Cannot get the name, such as defining/declaring a constructor, a method
that returns of type decltype(*this). It also lacks deduction guides.

This feature will be a very significant change to local classes as it also
provides a template that local classes don't have. However, this will only
be a syntactic sugar that would increase the readability.

:> I'm still 15 years old, and currently learning C++ but I have loads of
ideas to make C++ better, or worse (it depends)

Received on 2021-07-01 02:20:19