类型转换
代码位置: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);
}