| --- ( @ 2007-11-29 21:12:00 |
| Entry tags: | suxx |
isDerived: feel difference
C++
class base { public: int i; };
class child : public base { public: int j; };
class other { public: int z; };
template <typename D, typename B>
class IsDerived
{
struct No {}; struct Yes { No no[2]; };
static Yes Test(B*);
static No Test(...);
public: enum { Derived = sizeof(Test(static_cast<D*>(0))) == sizeof(Yes) };
};
template <class T>
bool function()
{
if (IsDerived<T, base>::Derived == 1)
return true;
else
return false;
}
int _tmain(int argc, _TCHAR* argv[])
{
assert(true == function<base>());
assert (true == function<child>());
assert (false == function<other>());
assert (false == function<int>());
return 0;
}
C#
class Program
{
class base_ { public int i; }
class child : base_ { public int j; }
class other { public int z; }
static bool function<T>() where T : new()
{
T t = new T();
if (t is base_)
return true;
else
return false;
}
static void Main(string[] args)
{
Debug.Assert(true == function<base_>());
Debug.Assert(true == function<child>());
Debug.Assert(false == function<other>());
Debug.Assert(false == function<int>());
}
}