I am unable to figure out why this code is returning false. I had the first version of partial specialization. It did not work, I tried with the second version. It did not work either.
UPDATE: I wanted to check if "Derived" is publicly derived from "Base".
UPDATE:
template<typename TDerived, typename TBase>
struct Derived_From
{
public:
static void constraints(TBase*, TDerived* ptr) { TBase* b = ptr; ignore(b); }
Derived_From() { void (*p)(TBase*, TDerived*) = constraints; ignore(p);}
};
I found the above code snippet in Strostrup's homepage. But, it does not let the code compile if the derived class is not publicly derived from Base.
template<class TBase, class TDerived>
struct IsDerived
{
public:
enum { isDerived = false };
};
template<class TBase>
struct IsDerived<TBase, TBase>
{
public:
enum { isDerived = true };
};
template<class TBase>
struct IsDerived<TBase&, TBase&>
{
public:
enum { isDerived = true };
};
int main()
{
cout << ((IsDerived<Base&, Derived&>::isDerived) ? "true" : "false")
<< endl;
cout << ((IsDerived<const Derived*, const Base*>::isDerived) ?
"true" : "false") << endl;
}
I always just use pointer initialization for this. Pointers implicitly convert only to a supertype (could be identity conversion or public base class), so it won't compile unless that relationship exists (and in the right direction).
e.g.
Parent* p = (Possibly_Derived*)0;
Oh wait, you're not wanting compilation to fail, but to set a variable? Here:
template<typename TParent>
bool is_derived_from( TParent* ) { return true; }
template<typename TParent>
bool is_derived_from( void* ) { return false; }
cout << is_derived_from<Parent>( (Possibly_Derived*)0 );
Here's a demo: http://ideone.com/0ShRF
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With