注:下文中的英文内容取自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);
}