C++ Logo


Advanced search

Re: [std-proposals] Extend std::type_info with more information

From: Phil Endecott <std_proposals_list_at_[hidden]>
Date: Thu, 11 Apr 2024 16:46:32 +0000
Jason McKesson <jmckesson_at_[hidden]>
> There are times when you need to pass an object of a known type
> through an intermediary that handles multiple such operations and
> therefore doesn't need to know what type you're passing. Callbacks,
> signal processing, things like that. In those cases, the sender and
> the receiver really ought to be on the same page as to what is being
> sent and received.
> *Precisely* what is being sent and received.
> I don't think it's good code to send an object of one type through
> this interface, but have the receiver be blind to exactly what that
> type was. Especially if that type uses *value semantics* the way `any`
> does.

Let me describe the situation in which I discovered a need for a
std::any -like type that would allow me to cast to a base class:

Consider a std::any used represent something like a "current selection" in
a GUI application.

I have a variety of abstract base classes ("interfaces") that the
application's objects may implement, including whatever is currently
stored in the selection.

User interface objects (such as menu items) may want to be enabled or
disabled depending on whether their action is appropriate for the current
selected object, and then invoke the action through the base class.

So for example I may have an abstract base class like this:

class Alignable
  enum Alignment { left, center, right };
  virtual void align(Alignment a) = 0;

Then I have concrete derived classes like this:

class Paragraph: public Alignable, ....

Then I have an alignment menu, which does something like this:

  align_menu.enabled =
    any_base_cast<Alignable>(&current_selection) != nullptr;

  align_menu.left.on_tap =
    any_base_cast<Alignable>(&current_selection) -> align(left);

Contrary to your claim, I believe that it's useful and not "bad code"
for code that receives an any-like type to not know its exact type,
but rather to operate on it through base classes that it does know

In cases where all parties know "*precisely* what is being sent and
received", a variant can be used.

Regards, Phil.

Received on 2024-04-11 16:46:39