什么是implicit_cast?我什么时候应该更喜欢implicit_cast 而不是static_cast?
最佳答案
我正在复制我对 answer this comment 的评论在另一个地方。
You can down-cast with
static_cast
. Not so withimplicit_cast
.static_cast
basically allows you to do any implicit conversion, and in addition the reverse of any implicit conversion (up to some limits. you can't downcast if there is a virtual base-class involved). Butimplicit_cast
will only accept implicit conversions. no down-cast, novoid*->T*
, noU->T
if T has only explicit constructors for U.
请注意,请务必注意强制转换和转换之间的区别。在下面没有类型转换进行
int a = 3.4;
但是从 double 到 int 发生了隐式转换。诸如“隐式转换”之类的东西不存在,因为转换始终是显式转换请求。 boost::implicit_cast
的名称结构是“使用隐式转换进行转换”的可爱组合。现在全部执行boost::implicit_cast
这是(解释here):
template<typename T> struct identity { typedef T type; };
template<typename Dst> Dst implicit_cast(typename identity<Dst>::type t)
{ return t; }
这个想法是为参数 t
使用非推断上下文。 .这样可以避免以下陷阱:
call_const_version(implicit_cast(this)); // oops, wrong!
想要写成这样
call_const_version(implicit_cast<MyClass const*>(this)); // right!
编译器无法推断模板参数的类型Dst
应该命名,因为它首先必须知道identity<Dst>
是,因为它是用于扣除的参数的一部分。但它又取决于参数Dst
( identity
可以明确地专门用于某些类型)。现在,我们得到了一个循环依赖,标准只是说这样一个参数是一个非推导上下文,并且必须提供一个显式的模板参数。
关于c++ - static_cast 和 Implicit_cast 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/868306/