在C ++中可以使用其他有用的转换 [英] What other useful casts can be used in C++

查看:123
本文介绍了在C ++中可以使用其他有用的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C ++附带四个内置版本。

C++ comes with four built-in casts.


  1. static_cast li>
  2. dynamic_cast

  3. const_cast li>
  4. reinterpret_cast

  1. static_cast
  2. dynamic_cast
  3. const_cast
  4. reinterpret_cast

皱眉 C(style *)cast

此外 boost 提供 lexical_cast ,您是否还有其他有用的角色,您使用或想要存在?

Additionally boost supplies a lexical_cast, are there any other useful casts that you use or would like to exist?

推荐答案

最喜欢和最喜欢的演员是 implicit_cast 。它只有在类型可以被隐式转换时才会成功。

My favorite and most loved cast is implicit_cast. It only succeeds if the types can be implicitly converted.

有用于将某些类型转换为 void * 或从某个派生类转换为基础选择一个重载函数或构造函数的特定实例),或者安全地添加const-qualifications和任何其他你真正需要隐式转换的情况,甚至 static_cast

Useful for conversion from some type into void* or from some derived class into a base (if you want to select a specific instance of an overloaded function or constructor) or to safely add const-qualifications and any other scenario where you really just need implicit conversions to happen and even static_cast is too powerful.

另请参阅 C ++如何选择要调用的重载

boost / implicit_cast.hpp 。如果你想要

boost/implicit_cast.hpp. You can add this to your code collection too, if you want

template<typename T> struct identity { typedef T type; };
template<typename Dst> Dst implicit_cast(typename identity<Dst>::type t)
{ return t; }

这篇关于在C ++中可以使用其他有用的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆