std :: any_cast而无需原始对象的类型

发布于 2025-02-03 06:56:12 字数 182 浏览 1 评论 0原文

是否可以使用std :: Any_cast而无需放入第一个模板参数(对象的类型任何覆盖)?我尝试使用any_cast< exptype(typeId(tocast).name())>,但它不起作用。

还尝试从一开始就存储对象类型,但这也无效,因为变量无法存储类型。

Is it possible to use std::any_cast without putting in the first template argument (the type of the object the any is covering)? I tried using any_cast<decltype(typeid(toCast).name())> but it didn't work.

Also tried to store the objects types from the beginning, but that also didn't work because variables can't store types.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

太傻旳人生 2025-02-10 06:56:13

C ++的基本原理之一是所有对象的类型在编译时已知。这是一个绝对的规则,也没有例外。

所讨论的对象的类型是std ::任何。仅当该类型在编译时也已知时,它才能转换为其他类型。

您会注意到std :: type_info :: name()不是constexpr表达式。返回的字符串仅在运行时才知道。您正在尝试将某些东西投入到只有在运行时才知道的对象。 C ++不起作用。

通常,每当发生这种情况时,几乎所有时间都将涉及在基类中调用虚拟方法。您可能需要重新设计您的类以使用继承和虚拟方法;使用其公共基类代替std ::任何;然后调用其虚拟方法。在某些情况下,std ::变体也可能起作用。

One of the fundamentals principles of C++ is that the types of all objects are known at compile time. This is an absolute rule, and there are no exceptions.

The type of the object in question is std::any. It is convertible to some other type only if that type is also known at compile time.

You will note that std::type_info::name() is not a constexpr expression. The returned string is known only at run time. You are attempting to cast something to an object whose type would only be known at run time. C++ does not work this way.

In general, whenever such a situation occurs, nearly all the time the correct solution will involve virtual methods getting invoked on a base class. You will likely need to redesign your classes to use inheritance and virtual methods; using their common base class instead of std::any; then invoking its virtual methods. In some situations std::variant may also work, too.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文