While going through some of the C++ concepts I stumbled upon std::is_base_of logic.
Googling around for logic produced the below code, but I am not able to understand it.
Could somebody explain me how it works?
template<typename D, typename B>
class IsDerivedFromHelper
{
class No { };
class Yes { No no[3]; };
static Yes Test( B* );
static No Test( ... );
public:
enum { Is = sizeof(Test(static_cast<D*>(0))) == sizeof(Yes) };
};
template <class C, class P>
bool IsDerivedFrom() {
return IsDerivedFromHelper<C, P>::Is;
}
When B
is a base class of D
, the call Test(static_cast<D*>(0))
resolves to Yes Test(B*)
. Otherwise, it resolves to No Test(...)
.
If B
is a base class of D
, the value of sizeof(Test(static_cast<D*>(0)))
is sizeof(Yes)
. Otherwise, it is equal to sizeof(No)
.
Yes
and No
are defined such that sizeof(Yes)
will never be equal to sizeof(No)
.
If B
is a base class of D
,
sizeof(Test(static_cast<D*>(0))) == sizeof(Yes)
evaluates to true
. Otherwise it evaluates to false
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.