c++ 17 ny_cast;失败隐式CTOR,抛出异常
我的我的
带有一个隐式ctor 我的(int i)
,我希望将int投入到我的身上,所以我有:
#include <any>
#include <iostream>
using namespace std;
struct My {
My(int i) { cout << "int ctor\n"; }
};
ostream& operator << (ostream& os, const My& m) {
os << "My object\n";
return os;
}
int main() {
any a = 1;
auto am = My(any_cast<int>(a));
cout << a.type().name() << ": " << any_cast<int>(a) << '\n';
cout << a.type().name() << ": " << any_cast<My>(a) << '\n';
return 0;
}
运行后,它打印出来:
int ctor
i: 1
i: terminate called after throwing an instance of 'std::bad_any_cast'
what(): bad any_cast
我期望那个any_cast&lt; my&gt;(a)
应该能够调用我的(a)
构造一个新对象,但实际上不是。
我有什么误解吗?
I've having My
with an implicit ctor My(int i)
, I wish to cast an int into My, so I have:
#include <any>
#include <iostream>
using namespace std;
struct My {
My(int i) { cout << "int ctor\n"; }
};
ostream& operator << (ostream& os, const My& m) {
os << "My object\n";
return os;
}
int main() {
any a = 1;
auto am = My(any_cast<int>(a));
cout << a.type().name() << ": " << any_cast<int>(a) << '\n';
cout << a.type().name() << ": " << any_cast<My>(a) << '\n';
return 0;
}
Upon running, it prints:
int ctor
i: 1
i: terminate called after throwing an instance of 'std::bad_any_cast'
what(): bad any_cast
I expected that any_cast<My>(a)
should be able to call My(a)
to construct a new object, but actually not.
Did I mis-undertand anything?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这根本不是
std :: Any_cast
工作的方式。从字面上看,它不是Egstatic_cast
IS之类的类型之间的铸件。您必须必须提供存储在
std ::任何
对象中的确切类型以访问其值(通过std :: Any_cast
)。不可能暗示任何转换。因为仅在运行时确定
std ::任何
中存储的类型允许转换。这显然是不可行的或不可能的。std ::任何
是工作的正确工具。特别是它将不允许您规避C ++的静态性质。This is simply not how
std::any_cast
works. It is not literally a cast between types like e.g.static_cast
is.You must provide the exact type stored in the
std::any
object to access its value (viastd::any_cast
). It is impossible to imply any conversions.Because the type stored in the
std::any
is only determined at runtime, the compiler would need to emit code for every possible type that could be stored in it and be convertible to the target type, if implicit conversions were allowed. That is clearly infeasible or impossible.There are only very few situations where
std::any
is the right tool for the job. In particular it will not allow you to circumvent the statically-typed nature of C++.不,
any_cast&lt; t&gt;(a)
在且仅当t
出现在a
中时才成功。是否在a
中有t
回答查询。不是是否有某种类型隐式转换为t
。在自己提取价值之后,您必须这样做。No,
any_cast<T>(a)
succeeds if and only ifT
is present ina
. It answers the query whether there isT
ina
. Not whether there is some type implicitly convertible toT
. You have to do that after extracting the value yourself.至于手册
a
应包含精确的类型我的
。它不调用转换构造函数。
As for the manual
a
should contain the exact typeMy
.It does not call converting constructors.