问题描述
什么是implicit_cast?当我应该preFER implicit_cast而不是的static_cast?
What is implicit_cast? when should I prefer implicit_cast rather than static_cast?
推荐答案
我从评论复制了我做出answer在另一个地方这条评论。
I'm copying over from a comment i made to answer this comment at another place.
您可以向下转换与的static_cast
。并非如此, implicit_cast
。 的static_cast
基本上可以让你做任何的隐式转换,此外,任何隐式转换的反向(达到一些限制,你可以,如果有一个虚拟的基线没有垂头丧气类涉及)。但 implicit_cast
将仅的接受隐式转换。没有向下转换,没有无效* - > T *
,没有 U->吨
如果T只有显式的构造妳。
请注意,一定要注意一个演员和一个转换之间的区别是很重要的。在下面没有投是怎么回事
Note that it's important to note the difference between a cast and a conversion. In the following no cast is going on
int a = 3.4;
但是,一个隐式转换,从双恰好INT。像一个隐式转换的东西是不存在的,因为投始终是明确的转换请求。这个名字构建的boost :: implicit_cast
是使用隐式转换投一个可爱的组合。现在整个实施的boost :: implicit_cast
的是这样的(解释here):
But an implicit conversion happens from double to int. Things like an "implicit cast" don't exist, since a cast is always an explicit conversion request. The name construct for boost::implicit_cast
is a lovely combination of "cast using implicit conversions". Now the whole implementation of boost::implicit_cast
is this (explained here):
template<typename T> struct identity { typedef T type; };
template<typename Dst> Dst implicit_cast(typename identity<Dst>::type t)
{ return t; }
我们的想法是使用非推导出上下文参数 T
。这将避免类似以下缺陷:
The idea is to use a non-deduced context for the parameter t
. That will avoid pitfalls like the following:
call_const_version(implicit_cast(this)); // oops, wrong!
什么是需要的是把它写像这样
What was desired is to write it out like this
call_const_version(implicit_cast<MyClass const*>(this)); // right!
编译器不能推断出什么类型的模板参数 Dst的
应的名字,因为它首先必须知道身份与LT; Dst的&GT;
是的,因为它是用于抵扣参数的一部分。但是,这又取决于参数 Dst的
(身份
可以明确专门用于某些类型)。现在,我们得到了一个循环依赖,为此,标准只是说这样的参数是一个非推导出的背景下,并且必须提供一个明确的模板参数。
The compiler can't deduce what type the template parameter Dst
should name, because it first must know what identity<Dst>
is, since it is part of the parameter used for deduction. But it in turn depends on the parameter Dst
(identity
could be explicitly specialized for some types). Now, we got a circular dependency, for which the Standard just says such a parameter is a non-deduced context, and an explicit template-argument must be provided.
这篇关于什么是static_cast并Implicit_cast之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!