【发布时间】:2019-12-17 14:40:59
【问题描述】:
您可以使用 any_cast 将 std::any* 类型转换为原始类型的指针。但是你怎么做相反的呢?
string h = “str”;
string *j = &h;
std::any *hh = reinterpret_cast<any*>(j);
cout << (*hh).type().name();
它不会起作用。无论我使用哪种类型,如果我取消引用结果指针并使用“.”访问成员或者我使用“->”来访问我的应用程序失败的指针上的相同成员。
我也尝试过 static_cast 和 dynamic_cast 但那甚至无法编译。
【问题讨论】:
-
std::any_cast不像你想象的那样工作。请参阅this 了解它的实际作用。 -
reinterpret_cast- 我不在乎你从什么投射或投射到什么,这可能是一个错误。 -
std::any a = h; std::any *hh = &a;是这样做的方法。不知道你为什么想要,你想达到什么目的? -
@AlanBirtles
std::any *hh = &h;是一个很大的数字。 -
@AlanBirtles 因为您不允许将指针转换为不相关的类型。
std::any*和std::string*不相关。这也不是你应该如何使用std::any。