转自:https://blog.youkuaiyun.com/xiaoc_fantasy/article/details/79570788
https://blog.youkuaiyun.com/weixin_40021744/article/details/88802969
1、向上转换
template<typename To, typename From>
inline To implicit_cast(From const &f) {
return f;
}
up_cast时应该使用implicit_cast替换static_cast
2、向下转换
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);
}
实例:
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<typename To, typename From>
inline To implicit_cast(From const &f) {
return f;
}
//MiddleA implicit_cast(Top const &top) {
// return top;
//}
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);
}
int main()
{
Bottom bottom;
Top top;
//Function(static_cast<MiddleB&>(top));
//Function(implicit_cast<MiddleA, Top>(top));
//Function(implicit_cast<MiddleA, Bottom>(bottom));
//Function(bottom);
//Function(static_cast<MiddleA&>(bottom));
MiddleB *pTop = ⊥
MiddleB *pBottom = down_cast<MiddleB *>(&top);
getchar();
return 0;
}