C++ 带有四个内置类型转换。
static_cast
dynamic_cast
const_cast
reinterpret_cast
并不是说对 C (style*)cast
不屑一顾。
另外 boost提供 lexical_cast , 是否还有其他有用的类型转换您使用或希望存在?
最佳答案
我最喜欢和最喜爱的 Actor 是 implicit_cast
。只有当类型可以被隐式转换时它才会成功。
用于从某种类型转换为 void*
或从某个派生类转换为基类(如果您想选择重载函数或构造函数的特定实例)或安全地添加 const 限定以及任何其他你真的只需要隐式转换的场景,甚至 static_cast
都太强大了。
另请阅读 How does C++ pick which overload to call .
boost/implicit_cast.hpp
.如果需要,您也可以将其添加到您的代码集合中
template<typename T> struct identity { typedef T type; };
template<typename Dst> Dst implicit_cast(typename identity<Dst>::type t)
{ return t; }
关于c++ - 在 C++ 中可以使用哪些其他有用的类型转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/862858/