muduo type.h 解析 C++类型转换技巧

29 篇文章 0 订阅

初始化

// 简化了 memset 的使用
inline void memZero(void* p, size_t n)
{
  memset(p, 0, n);
}

隐式转化

// 用于在继承关系中, 子类指针转化为父类指针;隐式转换
// inferred 推断,因为 from type 可以被推断出来,所以使用方法和 static_cast 相同
template<typename To, typename From>
inline To implicit_cast(From const &f)
{
  return f;
}

向下转化继承关系中的指针

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);
}

指针向上转化的过程中可以安心的使用 implicit_cast<> 因为都会成功,但是在指针向下的转化中你并不能确定 subclassOfFoo 一定是 foo 的子类,需要使用 dynamic_cast<>来动态的转化来确保没有问题。
在 debug 宏被定义的情况下使用 dynamic_cast<> 避免错误,在实际release版本中使用static_cast 提高速度。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值