Created
July 23, 2017 19:36
-
-
Save uxdxdev/6984706f83d45df931279751b50e7ce0 to your computer and use it in GitHub Desktop.
Implement a template function IsDerivedFrom() that takes class C and class P as template parameters. It should return true when class C is derived from class P and false otherwise.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
using namespace std; | |
class B { | |
}; | |
class A : public B { | |
}; | |
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; | |
} | |
// To execute C++, please define "int main()" | |
int main() { | |
// true if A derived from B | |
cout << IsDerivedFrom<A, B>(); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment