muduo types.h

转自:https://blog.csdn.net/xiaoc_fantasy/article/details/79570788

https://blog.csdn.net/weixin_40021744/article/details/88802969

1、向上转换

template
inline To implicit_cast(From const &f) {
  return f;
}

up_cast时应该使用implicit_cast替换static_cast

 

2、向下转换

template     // use like this: down_cast(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(0);
  }

#if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI)
  assert(f == NULL || dynamic_cast(f) != NULL);  // RTTI: debug mode only!
#endif
  return static_cast(f);
}

 

实例:

class Top {};
class MiddleA :public Top {};
class MiddleB :public Top {};
class Bottom :public MiddleA, public MiddleB {};

void Function(MiddleA& A)
{
    std::cout << "MiddleA Function" << std::endl;
}
void Function(MiddleB& B)
{
    std::cout << "MiddleB Function" << std::endl;
}

template
inline To implicit_cast(From const &f) {
    return f;
}

//MiddleA implicit_cast(Top const &top) {
//    return top;
//}
template     // use like this: down_cast(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(0);
    }

#if !defined(NDEBUG) && !defined(GOOGLE_PROTOBUF_NO_RTTI)
    assert(f == NULL || dynamic_cast(f) != NULL);  // RTTI: debug mode only!
#endif
    return static_cast(f);
}


int main()
{
    Bottom bottom;
    Top top;
    //Function(static_cast(top));
    //Function(implicit_cast(top));
    //Function(implicit_cast(bottom));
    
    //Function(bottom);
    //Function(static_cast(bottom));

    MiddleB *pTop = ⊥
    MiddleB *pBottom = down_cast(&top);
    getchar();
    return 0;
}

你可能感兴趣的:(muduo服务器)