C++中类型转换

注:下文中的英文内容取自Google开源代码中的注释。


C++中的四种类型转换函数。。。。


UPCASE and DOWNCASE

向上转换  和   向下转换

用于类的继承体系中,superclass 在上面,subclass在下面,

所以upcase就是从sub->super, 而downcase就是从super->sub

implicit_cast<ToType>(expr) 

// implicit_cast would have been part of the C++ standard library,
// but the proposal was submitted too late.  It will probably make
// its way into the language in the future.

 google的实现

template<typename To, typename From>
  inline To implicit_cast(From const &f) {
  return f;
 }

implicit_cast he static_cast 的区别:

implicit_cast 更安全。

原因如下:

 311 // When you upcast (that is, cast a pointer from type Foo to type
 312 // SuperclassOfFoo), it's fine to use implicit_cast<>, since upcasts
 313 // always succeed.  When you downcast (that is, cast a pointer from
 314 // type Foo to type SubclassOfFoo), static_cast<> isn't safe, because
 315 // how do you know the pointer is really of type SubclassOfFoo?  It
 316 // could be a bare Foo, or of type DifferentSubclassOfFoo.  Thus,
 317 // when you downcast, you should use this macro.  In debug mode, we
 318 // use dynamic_cast<> to double-check the downcast is legal (we die
 319 // if it's not).  In normal mode, we do the efficient static_cast<>
 320 // instead.  Thus, it's important to test in debug mode to make sure
 321 // the cast is legal!
 322 //    This is the only place in the code we should use dynamic_cast<>.
 323 // In particular, you SHOULDN'T be using dynamic_cast<> in order to
 324 // do RTTI (eg code like this:
 325 //    if (dynamic_cast<Subclass1>(foo)) HandleASubclass1Object(foo);
 326 //    if (dynamic_cast<Subclass2>(foo)) HandleASubclass2Object(foo);
 327 // You should design the code some other way not to need this.
 328


google 的downcase版本:

template<typename To, typename From>     // use like this: down_cast<T*>(foo);

  inline To down_cast(From* f) {                   // so we only accept pointers
    // Ensures that To is a sub-type of From *.  This test is here only
    // for compile-time type checking, and has no overhead in an
    // optimized build at run-time, as it will be optimized away
    // completely.
    if (false) {   // My add Why write this?  Ans. 快速注释掉代码
      implicit_cast<From*, To>(0);
    }

#if !defien(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI)

  assert(f == NULL || dynamic_cast<To>(f) != NULL);   // RTTI: debug mode only!

#endif

  return static_cast<To>(f);

}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值