muduo源码阅读笔记之类型转换

类型转换

代码位置:base/Types.h
这里定义了两种类型转换,implicit_cast和down_cast
其中implicit_cast定义如下,可以看到只是封装了一个隐式转换,它与static_cast的区别在于,static_cast允许向上和向下转型,而implicit_cast只允许向上转型
https://stackoverflow.com/questions/868306/what-is-the-difference-between-static-cast-and-implicit-cast
且implicit_cast与const_cast相比来说,前者不允许const指针转换成非const指针,而后者允许
所以使用implicit_cast比static_cast和const_cast安全

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

down_cast定义如下,其主要功能是提供安全的向下转型,其中先使用implicit_cast确定下To类型真的是From的子类型(通过将From和To对调),接着使用dynamic_cast判断是否可以将From类型向下转型成To类型(即判断From类型指针是否真的指向To类型),注意dynamic_cast对于没有虚函数的基类会拒绝转型。

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)
  {
    implicit_cast<From*, To>(0);
  }
#if !defined(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、付费专栏及课程。

余额充值