Skip to content

Instantly share code, notes, and snippets.

@uxdxdev
Created July 23, 2017 19:36
Show Gist options
  • Save uxdxdev/6984706f83d45df931279751b50e7ce0 to your computer and use it in GitHub Desktop.
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.
#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