std :: any_cast而无需原始对象的类型
是否可以使用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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
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 aconstexpr
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 situationsstd::variant
may also work, too.