static_cast 和 Implicit_cast 有什么区别?

什么是implicit_cast?我什么时候应该更喜欢implicit_cast而不是static_cast?

What is implicit_cast? when should I prefer implicit_cast rather than static_cast?

推荐答案

我正在复制我对 在另一个地方回答此评论.

您可以使用 static_cast 进行向下转换.implicit_cast 并非如此.static_cast 基本上允许您进行任何隐式转换,以及任何隐式转换的反向操作(达到某些限制.如果涉及虚拟基类,则不能向下转换).但是implicit_cast 将只接受隐式转换.没有向下转换,没有 void*->T*,没有 U->T 如果 T 只有 U 的显式构造函数.

You can down-cast with static_cast. Not so with implicit_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). But implicit_cast will only accept implicit conversions. no down-cast, no void*->T*, no U->T if T has only explicit constructors for U.

请注意,重要的是要注意强制转换和转换之间的区别.在下面没有演员进行

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;

但是从 double 到 int 的隐式转换发生了.诸如隐式转换"之类的东西不存在,因为转换始终是显式转换请求.boost::implicit_cast 的名称构造是使用隐式转换进行转换"的可爱组合.现在 boost::implicit_cast 的整个实现是这样的(解释了 此处):

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!

想要的是这样写出来

call_const_version(implicit_cast<MyClass const*>(this)); // right!

编译器无法推断模板参数 Dst 应该命名的类型,因为它首先必须知道 identity 是什么,因为它是用于推导的参数.但它反过来又取决于参数 Dst(identity 可以明确地专门用于某些类型).现在,我们得到了一个循环依赖,标准只是说这样的参数是一个非推导的上下文,并且必须提供一个显式的模板参数.

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.

相关文章