c++ - static_cast 和 Implicit_cast 有什么区别?

标签 c++ boost static-cast boost-implicit-cast

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

最佳答案

我正在复制我对 answer this comment 的评论在另一个地方。

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.

请注意,请务必注意强制转换和转换之间的区别。在下面没有类型转换进行

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/

相关文章:

c++ - 使用 Visual Studio 2005 展开小循环

c++ - 在调用 async_write 时我是否需要关心套接字的生命周期?

c++ - 为什么使用 static_cast<int>(x) 而不是 (int)x?

c++ - opencv:填充 cv::mat 的不同方法

c++ - 在 Fedora 24 上构建 SFML 链接错误 : error while loading shared libraries: libsfml-graphics. so.2.4:无法打开共享对象文件

c++ - CMake问题:如何使用vcpkg自动安装依赖项?

c++ - boost C++ : how to return file from folder via tcp?

c++ - boost::spirit:语义 Action block 中的多个语句

C++我们什么时候应该更喜欢使用两个链接的static_cast而不是reinterpret_cast

c++ - 使用 static_cast 的无效类型转换,我应该使用什么正确的转换?